【bug消除!】ios中h5 文字渐变色和超出省略的问题

666 阅读2分钟

需求

文字超出省略展示... 而且文字增加渐变色

实现

乍一看很简单

  1. 增加渐变色
    background-image: linear-gradient(to top, red, purple);
    -webkit-background-clip: text;
    color: transparent;
    font-size: 30px;
    display: inline-block;
  • background-image 属性为该文字区域设置了一个渐变的背景色
  • color:transparent 把这个区域里的文字颜色设置成了透明色

或者设置-webkit-text-fill-color: transparent;

  • background-clip:text 将背景裁剪成了文字的前景色
  1. 超出省略号,万年老三行+最大宽度
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  max-width: 200px;

然后效果

image.png

然而在ios中看到

image.png

省略号没了???

猜测可能是因为省略号是浏览器计算完宽度后,后加上的,没有适配之前的css,只根据color: transparent; 显示为了透明色

那我给文字一个默认颜色试一下

首先把之前设置的 color: transparent;改成 -webkit-text-fill-color: transparent; 避免覆盖,然后增加color:red

发现并没有作用

换一种渐变实现方式试一下

mask实现渐变

使用css3的mask

首先给元素增加text属性

<div text="测试渐变测试渐变测试渐变测试渐变测试渐变" class="cssTwo">
        测试渐变测试渐变测试渐变测试渐变测试渐变
      </div>

然后css中设置

.cssTwo {
    position: relative;
    color: red;
    font-size: 30px;
}
.cssTwo:before {
    content: attr(text); // 取text属性的文案
    position: absolute;
    z-index: 10;
    color: purple;
    -webkit-mask: linear-gradient(to top, transparent, purple);
}

然后增加省略号css

元素和before需要都增加

最后为

 .cssTwo {
    position: relative;
    color: red;
    font-size: 30px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    max-width: 100px;
  }
  .cssTwo:before {
    content: attr(text);
    position: absolute;
    z-index: 10;
    color: purple;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    max-width: 100px;
    -webkit-mask: linear-gradient(to top, transparent, purple);
  }

效果为

image.png

在ios中

image.png

虽然解决的问题,但是目前css mask的兼容性还不太好,建议慎用~

image.png

最简单的碰到这种情况可以用js处理一下增加省略号吧~