javascript - vue 如何取得元件本身高度
世界只因有你
世界只因有你 2017-06-26 10:58:50
0
5
1182

由於要做一個可變化長高的彈出框,需要定位,彈出框可能在底部彈出也可能在頭部彈出,但內容由於是可變的,需要計算它的高度來顯示向上彈還是向下彈,目前在組件內如何得到他的高度
目前我的做法是在created()中使用classname得到組件的p但由於初始在 data()中將元件高度預設了0,
created改變data()中的height,但無法得到p

created() {

let cur = document.querySelectorAll("p[class='Pop-Over']");
console.log(cur);
let curHeight = cur.height;
console.log(curHeight);
}

列印結果curHeight為undefind,求辦法

世界只因有你
世界只因有你

全部回覆(5)
给我你的怀抱

element.offsetHeight
// 在vue中請使用ref獲取真實DOM
// 在mounted鉤子中調用,該鉤子是DOM渲染完之後觸發的

曾经蜡笔没有小新

雷雷

学霸

created勾子 dom節點還沒有插入進頁吧,需要在mounted勾子函數中調用
而且獲取到元素的高度,是用dom.clientHeight吧,或者dom.getBoundingClientRect().height吧

漂亮男人

@林小新由於我在調用時,使用了v-if所以每次設為true它才會創建,所以可以放在created中,但你這樣也讓我知道了nextTick這個東西,沒用過,但先按你的試試。
目前暫由於最外層p是沒有高度的,只能透過取子p的高度累加成為它的高度,這種做法只是折中解決,可能是我寫組件時沒有考慮到這些。

this.$nextTick(() => {

      let cur = document.querySelectorAll("p[class='Pop-Over']");

// console.log(cur);

      let curHeight = 0;
      cur[0].childNodes.forEach(function (item, index, array) {

// console.log(typeof item.clientHeight);

        curHeight += (typeof item.clientHeight) === 'number' ? item.clientHeight : 0;
      });
      });
          

如果沒有更好答案,我會採納你的

phpcn_u1582

取得實際的大小 .clientWidth和.clientHeight
並沒有.height這種取得方法,所以才undefined

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!