那些你不知道的 getClientRects()

1.getClientRects()。是能夠獲取內聯元素的內容有多少行

最近一個交互,在限定文字展示是5行,超過5行,則在後面添加。。。展開。若是沒有展開二字,咱們通常用css就能完成了。可是爲了交互更人性化javascript

text-overflow:
-o-ellipsis-lastline;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 5;
-webkit-box-orient: vertical;

來看看代碼,是如何實現的,必定要弄一個默認的span來判斷行數,獲得5行嗯能顯示什麼文字。而後記錄下來css

let txtDom = this.$refs.textContainer;
            txtDom.innerHTML = originalTxt; //第一次所有渲染
            let showtxtdom = originalTxt;
            let texLength = txtDom.getClientRects();
            let h = getLength(texLength);
            let tl = 0;
            if (h <= 5) {
              obj.unfoldFlag = false;
            } else {
              obj.unfoldFlag = true;
            }
            
             while (h > 5) {
              var step = 1;
              if (/<br\/>$/.test(showtxtdom)) {
                //回退的時候,若是碰到換行要總體替換
                step = 5;
              }
              showtxtdom = showtxtdom.slice(0, -step);
              //console.log(showtxtdom);
              txtDom.innerHTML =
                showtxtdom +
                '<span>...</span><span class="comm-item-content-spread-s">展開</span>';
              // console.log(txtDom.innerHTML);
              h = getLength(txtDom.getClientRects());
              tl += step;
            }obj.showTxt = showtxtdom;
            //點贊是不是已經默認的
            obj.statedefaut = item.state;
            obj.imgsrcselect =
              "http://img.58cdn.com.cn/chinahr/img/agree_ic_sel@3x.gif?" +
              new Date().getTime();
            let regroupdata = Object.assign({}, obj, item);
            return regroupdata;
          });
          // console.log(newlist);
          //this.$set(this.commentListdata.commentList, newlist);
          this.commentListArrObj = this.commentListArrObj.concat(newlist);
          this.commentListdata = communitydetailData.data;
          this.commentListdata.commentList = this.commentListArrObj;
          // console.log(this.commentListdata);
          return;
        }

2.getBoundingClientRect() 獲取盒模型,元素的高度和定位,left +top.在vue裏面常常遇到

Element.getBoundingClientRect().width =  border-left-width + padding-left + width + padding-right + border-right-width

Element.getBoundingClientRect().height =  border-top-width + padding-top + height + padding-bottom + border-bottom-width

3.$nextTick 的應用/nextTick:在下次 DOM 更新循環結束以後執行延遲迴調。

  • 不少時候咱們須要作到,動態算content的高度,就要手動減去頭部+尾部的高度。咱們須要等到數據加載完成以後,在作操做
  • 方法就是監聽數據的變化,而後在監聽裏面作搞的元算vue

    watch: {
         commentListdata: function() {
           this.$nextTick(() => {
             //console.log("--nextTick--");
             this.wrapperHeight = document.documentElement.clientHeight - this.$refs.wrapper.getBoundingClientRect().top;
             this.hasnowrapHeight = this.wrapperHeight - this.$refs.commmainwrap.getBoundingClientRect().height - this.$refs.commfootwrap.getBoundingClientRect().height;
           });
         }
       }
相關文章
相關標籤/搜索