首页 > 技术文章 > 小程序操作DOM以及JS求取字符串算法(前端网备份)

lsc-boke 2019-06-10 11:41 原文

 //js获取字符串的字节长度
//这套算法一个汉字2字节,字母符号1字节,按一行40个字节算4行
  getLength:function(val){
    var str = new String(val);
    var bytesCount = 0;
    for (var i = 0, n = str.length; i < n; i++) {
      var c = str.charCodeAt(i);
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
        bytesCount += 1;
      } else {
        bytesCount += 2;
      }
    }
    return bytesCount;  
  },
  onReady: function () {
    var that =this;
    setTimeout(function () {
      //要延时执行的代码
      var query = wx.createSelectorQuery();
      query.select('.pContent').boundingClientRect()
      query.exec((res) => {
        console.log(res);
        var pContentHeight = res[0].height;
        console.log("ready", pContentHeight);
        if (pContentHeight < 82 || pContentHeight==87) {
          that.setData({
            hidden: true
          });
        }
        that.setData({
          pContentHeight: pContentHeight
        });
      })
    },300) 

  },

初始化DOM求高度是有BUG的,只能第一次渲染后求,不加延迟有时候求不到值,加了延迟第一面效果不好

推荐阅读