获取不正确的offsetWidth和offsetHeight值 [英] Get incorrect offsetWidth and offsetHeight values

查看:161
本文介绍了获取不正确的offsetWidth和offsetHeight值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的angular2代码.

Here is my angular2 code.

模板

<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而引起的.您知道什么解决方案吗?

The problem is the printed values are different for each time loading. I guess this issue is due to the browser have not completed loading the div. Do you know what is the solution for this?

推荐答案

您可以使用

MutationObserver

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

Probably the biggest audience for this new api are the people that write JS frameworks, [...] Another use case would be situations where you are using frameworks that manipulate the DOM and need to react to these modifications efficiently ( and without setTimeout hacks! ).

在这里,您可以使用它来检测元素的变化:

Here is how you can use it to detect changes in elements :

// 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中使用它并刷新偏移量大小.您可以说得更具体些,只检测一些突变,然后才提取偏移量.

For your case, you could use it inside your ngAfterViewInit and refresh your offsets size. You can be more specific and only detect some mutations, and only then extract your offsets.

更多信息:

doc: https://developer.mozilla.org/zh- 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. 
// 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;
}

.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和offsetHeight值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆