前端技术~

返回指定行数文本

2017-11-24  本文已影响5人  Armin0202

场景

缩略显示 全文显示

方案策略


方案代码

/**
 * el: 文本所在的DOM元素
 * text: 文本内容
 * line: 指定返回行数
 * return { lineClamp: 是否进行了剪切, text: 返回的文本 }
 */ 
function lineClamp(el, text, line) {
        if (!el || !text) return { lineClamp: false, text: '' }
        const elCss = window.getComputedStyle(el)
        const elWidth = parseFloat(elCss.getPropertyValue('width'))
                        - parseFloat(elCss.getPropertyValue('padding-left'))
                        - parseFloat(elCss.getPropertyValue('padding-right'))
        const elFontSize = parseFloat(elCss.getPropertyValue('font-size'))
        const wordsLimit = Math.floor((elWidth * line) / elFontSize)

        let breakpoint = -1
        let words = 0
        for (let num = 0, len = text.split('').length; num < len; num += 1) {
          words += text[num].charCodeAt() > 255 ? 1 : 0.5
          breakpoint += text[num].charCodeAt() > 255 ? 1 : 0.9
          if (Math.ceil(words) >= wordsLimit) {
            break
          }
        }

        if (text && text.length >= wordsLimit) {
          return { lineClamp: true, text: `${text.substring(0, breakpoint - 2)}...` }
        }
        return { lineClamp: false, text }
      }

上一篇 下一篇

猜你喜欢

热点阅读