【问题标题】:How to observe changes of computed css properties in a vanilla JS ES6 custom element如何在 vanilla JS ES6 自定义元素中观察计算的 css 属性的变化
【发布时间】:2019-12-10 11:34:56
【问题描述】:

我正在尝试在 vanilla JS 中构建一个响应式自定义元素,该元素可以响应对其计算尺寸的更改。我已经成功地观察到明确定义的属性/属性的变化。但是,我想知道是否可以观察自定义元素的计算属性的变化。例如:

class Custom_element extends HTMLElement {
  generate_html() {
    return `
        <style>
            :host {
                display:block;
            }          
            #element_wrapper {
                border: 1px solid grey;
                max-height     : 100%;
                max-width      : 100%; 
                min-height     : 100%;
                min-width      : 100%;            
            }
        </style>
        <div id="element_wrapper">
            <slot></slot>
        </div>
        `
  };

  constructor() {
    super();
    this.root = this.attachShadow({
      'mode': 'open'
    });
    this.root.innerHTML = this.generate_html();
  }

  static get observedAttributes() {
    return ['height', 'width'];
  }

  attributeChangedCallback(name, oldVal, newVal) {
    console.log(name, oldVal, newVal) //Is it possible to fire this when the css computed height/width properties change?
  }

}


window.customElements.define('custom-element', Custom_element);
#container {
  width: 100px;
  height: 100px;
}

#container:hover {
  width: 200px;
  height: 200px;
}
<div id='container'>
  <custom-element>
    Slot Content
  </custom-element>
</div>

当您将鼠标悬停在#container 元素上并更改自定义元素的计算高度/宽度时,是否可以触发 attributeChangedCallback()?

【问题讨论】:

  • ResizeObserver 可能对您的用例有所帮助,尽管它仍处于试验阶段且缺乏浏览器支持。
  • @Bergi 是的,这就是我要找的。我一直在试图弄清楚如何使用observedAttributes 回调来让它工作。谢谢!!!
  • heightweight 不是 DOM 节点的属性。甚至 CSS 样式也没有改变,只有 computed 尺寸。如果没有某种resize 事件(不幸的是它只在window),我想投票clientWidth/clientHeight 将是你唯一的机会

标签: javascript css dom custom-element computed-style


【解决方案1】:

正如@Bergi 在 cmets 中指出的那样,ResizeObserver 正是我想要的。显然有一个 polyfill 可以帮助支持一些较旧的浏览器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多