获取不正确的offsetWidth和offsetHeight值

loi*_*mai 7 html angular

这是我的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>
Run Code Online (Sandbox Code Playgroud)


零件


    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;
}
Run Code Online (Sandbox Code Playgroud)

问题是每次加载的打印值都不同.我猜这个问题是由于浏览器还没有完成加载div.你知道这是什么解决方案吗?

kem*_*sky 5

您必须在渲染周期后安排对“offsetWidth”的调用,angular 在微任务队列的末尾执行 draw,因此您可以尝试setTimeout(..., 0)Promise.resolve().then(...)在 zonejs 之外运行。希望能帮助到你。


mad*_*oue 5

您可以使用来检测尺寸变化

突变观察者

此新api的最大听众可能是编写JS框架的人,另一个用例是您正在使用操纵DOM的框架并需要对这些修改做出有效反应的情况(并且没有setTimeout hack! )。

这是使用它来检测元素更改的方法:

// 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();
Run Code Online (Sandbox Code Playgroud)

对于您的情况,您可以在内部使用它ngAfterViewInit并刷新偏移量大小。您可以更具体一些,只检测一些突变,然后才提取偏移量。

更多信息 :

doc:https//developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver

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

演示

// 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();
Run Code Online (Sandbox Code Playgroud)
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. 
// N.B 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;
}
Run Code Online (Sandbox Code Playgroud)
.slider-horizontal {
  border: 2px solid red;
  width: 210px;
  height: 20px;
  background: grey;
}
Run Code Online (Sandbox Code Playgroud)