LitElement如何找出元素的宽度

问题描述

如何在Lit-Element中找到HTML元素的宽度知道,我无法找到如何使用@query

import { LitElement,html,query } from 'lit-element';

class MyElement extends LitElement {
  @query('#first')
  first;

  render() {
    return html`
      <div id="first">I want to kNow the size of this div</div>
      <div id="second">and set size to this div</div>
    `;
  }
}

解决方法

您可以使用 window.getComputedStyle() 函数获取任何元素的宽度和任何其他 CSS 属性。

import { LitElement,html,query } from 'lit-element';

class MyElement extends LitElement {    
  render() {
    return html`
      <div id="first">I want to know the size of this div</div>
      <div id="second">and set size to this div</div>
    `;
  }

  updated() {
     const elem = this.shadowRoot.querySelector('#first');
     this._width = getComputedStyle(elem).getPropertyValue('width');
     console.log(this._width);
  }
}