簡體   English   中英

獲取不正確的 offsetWidth 和 offsetHeight 值

[英]Get incorrect offsetWidth and offsetHeight values

這是我的 angular2 代碼。

模板

 <div #picker class="slider"> <div class="slider-track"> <div #sliderSelectionEl class="slider-selection"></div> <div #sliderHandle1 class="slider-handle"></div> <div #sliderHandle2 class="slider-handle"></div> </div> <div #tooltipEl class="tooltip"> <div class="tooltip-arrow"></div> <div #tooltipInner class="tooltip-inner"></div> </div> <input type="text" class="span2" value="" id="sl2"><br/> </div>


成分

import {Component, OnInit, Input, ViewChild, ElementRef, Renderer} from '@angular/core';
    export class SliderComponent implements OnInit {
      @ViewChild('picker') picker: ElementRef;

      constructor(private renderer: Renderer, private el: ElementRef) {

      }

      ngAfterViewInit() {
        this.renderer.setElementClass(this.picker.nativeElement, 'slider-horizontal', true);

        console.log(this.picker.nativeElement.offsetWidth);
        console.log(this.picker.nativeElement.offsetHeight);
      }
    }

 .slider-horizontal { width: 210px; height: 20px; }

問題是每次加載時打印的值都不同。 我猜這個問題是由於瀏覽器沒有完成加載div。 你知道解決這個問題的方法是什么嗎?

您可以使用以下方法檢測尺寸變化

突變觀察者

可能這個新 api 的最大受眾是編寫 JS 框架的人,[...] 另一個用例是您使用框架來操作 DOM 並且需要有效地對這些修改做出反應的情況(並且沒有 setTimeout hacks! )。

以下是如何使用它來檢測元素的變化:

// select the target node
var target = document.querySelector('#some-id'); // or 

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation.type);
    });
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true }

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();

對於您的情況,您可以在ngAfterViewInit使用它並刷新您的偏移量大小。 您可以更具體,只檢測一些突變,然后才提取您的偏移量。

更多信息 :

文檔: https : //developer.mozilla.org/en-US/docs/Web/API/MutationObserver

兼容性: https : //caniuse.com/#feat=mutationobserver

演示

 var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation); if(mutation.attributeName == 'class') // detect class change /* or if(mutation.target.clientWidth == myWidth) */ showOffset(mutation.target); observer.disconnect(); }); }); var config = { attributes: true} var demoDiv = document.getElementById('demoDiv'); var logs = document.getElementById('logs'); // wait for document state to be complete if (document.readyState === "complete") { ngAfterViewInit(); } document.onreadystatechange = function () { if (document.readyState === "complete") { ngAfterViewInit(); } } // observe changes that effects demoDiv + add class function ngAfterViewInit(){ observer.observe(demoDiv, config); demoDiv.classList.add('slider-horizontal'); } // show offsetWidth + height. // NB offset width and height will be bigger than clientWidth because I added a border. If you remove the border you'll see 220px,20px function showOffset(element){ offsetMessage = "offsetWidth:" + demoDiv.offsetWidth + " offsetHeight: " + demoDiv.offsetHeight; console.log(offsetMessage); logs.innerHTML = offsetMessage; }
 .slider-horizontal { border: 2px solid red; width: 210px; height: 20px; background: grey; }
 <div id='demoDiv'> I am a demo div </div> <div style="margin-top: 20px;"> logs : <span id='logs' style=" padding: 5px; border: 1px solid black"></span></div>

您必須在渲染周期后安排對 'offsetWidth' 的調用,angular 在微任務隊列的末尾執行 draw,因此您可以嘗試setTimeout(..., 0)或在Promise.resolve().then(...)運行Promise.resolve().then(...) zonejs 的。 希望能幫助到你。

為了獲得正確的偏移值,您可以使用: ngAfterContentChecked 和 AfterContentChecked 接口。

每次更改檢測運行后都會調用此方法。 因此,在此方法中使用標志(或計數器)和 setTimeOut:

if (this.counter <= 10) {
      // this print offsetwidth of my element
      console.log('mm ' + this.container.nativeElement.offsetWidth);


      // setTimeOut allow to run another changedetection 
      // so ngAfterContentChecked will run again
      setTimeout(() => { }, 0);

      //you could use a counter or a flag in order to stop getting the right width
      this.counter++;
    }

希望能幫助到你! 隨意評論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM