javascript – 如何观看DOM对象属性?

我想看一个DOM节点属性,但我似乎无法让它工作.

在我的小部件中,我尝试了以下内容.

startup: function() {
  this.inherited(arguments);

  // First try using the dojo 1.6 watch.
  // I'm setting the property of the widget
  // to reference the DOM node's offsetWidth property
  this.width = this.domNode.offsetWidth;
  this.watch("width", function() {
    console.debug('Width changed to ' + this.domNode.offsetWidth )
  })

  // Does this.width contain a reference or a copy of this.domNode.offsetWidth?

  // Second try, the Mozilla watch
  this.domNode.watch("offsetWidth", function() {
    console.debug('Width changed to ' + this.domNode.offsetWidth )
  })
}

解决方法:

I’m would like to watch a DOM node
property but I can’t seem to get it to
work.

通过将Mozilla的监视直接添加到DOM节点,您无法使其工作.

http://james.padolsey.com/javascript/monitoring-dom-properties/提到使用setInterval,onpropertychange(仅限IE)和DOMSubtreeModified(还有其他此类标准DOM修改事件,如DOMAttrModified,但您必须检查浏览器支持).标准DOM修改事件仅在更改DOM属性时才起作用,而不是等效属性(尽管您可以通过initMutationEvent从JS触发突变事件):

<input />
<script>
window.onload = function () {
  var ct=0;
  document.addEventListener('DOMAttrModified', function () {
      alert('Value modified ' + (++ct) + ' times');
  }, false);

  var input = document.getElementsByTagName('input')[0];

  input.setAttribute('value', 5); // Triggers the event
  input.value = 15; // Though it sets the value, it doesn't trigger the event

};
</script>

// First try using the dojo 1.6 watch.
// I’m setting the property of the
widget // to reference the DOM
node’s offsetWidth property
this.width = this.domNode.offsetWidth;
this.watch(“width”, function() {
console.debug(‘Width changed to ‘ + this.domNode.offsetWidth ) })

您可以使用Dojo API在此监视width属性的设置,但这似乎不会为您跟踪DOM节点(尽管http://dojotoolkit.org/features/1.6/widget-watch似乎表明它确实如此).例如,你可以这样做:

widget.set('width', 100);

然后可以修改上面的监视事件以动态更改DOM宽度(但不是offsetWidth,因为这是一个只读属性).

但是,您似乎正在尝试检测automaticoffsetWidth计算更改,而不是您自己的更改.在这一点上,对你来说最好的解决方案似乎是setInterval.

// Does this.width contain a reference
or a copy of this.domNode.offsetWidth?

this.domNode.offsetWidth之后的副本是一个数字,在JavaScript中,非对象类型将始终按值复制.

// Second try, the Mozilla watch
this.domNode.watch(“offsetWidth”,
function() {
console.debug(‘Width changed to ‘ + this.domNode.offsetWidth )
})

如果能够工作(并且没有),则需要在函数内部使用this.offsetWidth,因为Mozilla将回调设置为被监视对象的回调.

相关文章

我有一个网格,可以根据更大的树结构编辑小块数据.为了更容易...
我即将开始开发一款教育性的视频游戏.我已经决定以一种我可以...
我正在使用带有Grails2.3.9的Dojo1.9.DojoNumberTextBox小部...
1.引言鉴于个人需求的转变,本系列将记录自学arcgisapiforja...
我正在阅读使用dojo’sdeclare进行类创建的语法.描述令人困惑...
我的团队由更多的java人员和JavaScript经验丰富组成.我知道这...