index.js 3.29 KB
/**
 *
 * @param {*} str  字符串
 * @param {*} originLen 设置的width
 * @param {*} line 行数 默认1行省略
 * @returns
 * len :字节数,不是长度,该方法 是按字节数来截取,为了兼容截取后的长度一致问题,所以采用字节数来截取
 * 假设 200px的宽度 一个字节10px,减3是做了兼容处理,有可能字符比较短,越长的字符截取后,留下的空白越明显
 */
//  ((200 / 10) - 3) * line  , 60%的比例添加省略号
export const handlerFn = (str, originLen, line = 1) => {
  // var len = (Math.floor(originLen / 16) - 3) * line
  var len
  var temp
  var icount = 0
  var totalIcount = 0
  var stren = ''
  //这段正则表示匹配所有汉字以及全角字符
  var patrn = /[^\x00-\xff]/
  console.log('length',len,str.length)
  // if (len > str.length) {
  //   return str
  // }
  for (var i = 0; i < str.length; i++) {
      temp = str.substr(i, 1)
      if (patrn.exec(temp) == null) {
        totalIcount = totalIcount + 1
      } else {
        totalIcount = totalIcount + 2
      }
  }
  console.log('totalIcount',totalIcount)
  len = Math.floor(totalIcount * 0.7) - 2
  // len = (str.length * 2 * 0.5 * line) - 2
  for (var i = 0; i < str.length; i++) {
    if (icount < len - 1) {
      temp = str.substr(i, 1)
      if (patrn.exec(temp) == null) {
        icount = icount + 1
      } else {
        icount = icount + 2
      }
      stren += temp
    } else {
      break
    }
  }
  console.log('stren: ', stren)
  return stren + '...'
}

/**
 * 根据指定宽度截取字符串
 * @param desc 原始字符串
 * @param width 该显示的宽度
 * @param fontsize 字体大小  12px
 * @returns {string} 截取后的字符串
 */
export function getStrByWith(desc, width, fontsize) {
  // console.log('desc: ', desc);
  var span = document.createElement('span')
  span.id = 'cut'
  span.style.visibility = 'hidden'
  span.style.fontSize = fontsize
  span.style.whiteSpace = 'nowrap'
  document.body.appendChild(span)
  var boo = false
  var temp = '' // 存放截断字符串
  for (var j = 0; j < desc.length; j++) {
    // desc是目标字符串,
    temp += desc[j]
    span.innerText = temp
    // console.log('span.offsetWidth', span.offsetWidth, width)
    if (span.offsetWidth > width) {
      boo = true
      break
    }
  }
  document.body.removeChild(span)
  if (boo) temp += '...'
  return temp
}

// scope.row[item.prop].length >= Math.ceil((item.width - 36) / 14) * item.line"
const lineEllipsis = (value, columnWidth, line = 1) => {
  // console.log('value: ', value);
  if (!value) return ''

  // 假设一行的宽是字的个数10   160px的宽度  一个汉字16px
  // 单元格左右的宽为16
  // const strleng = Math.ceil((columnWidth-36)/14) * line - 2
  const strleng = Math.ceil((columnWidth - 36) / 14) * line - 2
  if (value.length > strleng) {
    // return value.substring(0, strleng) + '...'
    // return handlerFn(value,columnWidth,line )
    columnWidth = Math.floor(columnWidth * 0.6) - 30
    return getStrByWith(value, columnWidth, '14px')
  }
}

/**
 * 表格项内容为空 null,undefined,换为 -- 
 * 数字零还是显示0
 */

export const tableCellFormat = (value) =>{
  if(value === null || value === undefined || value === '') {
    return '--'
  }
  return value
}




export default {
  lineEllipsis,
  tableCellFormat
}