-webkit-box-orient:vertical 失效

首发地址-webkit-box-orient:vertical 失效

问题引出

-webkit-box-orient:vertical 属性常用在多行文本溢出

譬如这段超出 2 行文本溢出的代码,眼看好像没啥问题(火狐没这个属性,自然不支持)

.box {
    
    
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-all;
}

可是现在哪怕在 chrome 都失效了,为啥?

是因为我用了 vue-cli 然后集成了部分 css 插件,所以经过脚手架打包后,脚手架把 -webkit-box 开头的属性都过滤掉了

为了防止属性被过滤,可以从下面 3 种方法考虑:

解决方法

添加注释的方法

.box {
    
    
  /* autoprefixer: ignore next */
  -webkit-box-orient: vertical;
}

.box {
    
    
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}

动态添加 css

当然如果你和配合开发的同事的脚手架/其他环境不太一样,有可能会引发 cli 的警告。毕竟注释方法不太通用,那么可以考虑 JS 动态添加 css 的方式

详细的可以看下这篇文章:JS 动态插入 css

直接贴出代码:

var style = document.createElement('style')
var cssCode = `
        .ellipse-2{
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
        }
      `
style.type = 'text/css'
style.rel = 'stylesheet'
try {
    
    
  //for Chrome Firefox Opera Safari
  style.appendChild(document.createTextNode(cssCode))
} catch (ex) {
    
    
  //for IE
  style.styleSheet.cssText = cssCode
}
var head = document.getElementsByTagName('head')[0]
head.appendChild(style)

猜你喜欢

转载自blog.csdn.net/Jioho_chen/article/details/108311952