DOM Element Width before Appended to DOM

后端 未结 6 1726
渐次进展
渐次进展 2020-12-09 02:27

I\'m sure the answer is no, but is it possible to determine the width of an element before it is appended to the DOM?

Once it\'s appended, I know I

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 03:14

    /**
     * Get bounding client rect for an element (not exists at current DOM tree)
     * @param {!HTMLElement} el
     * @return {!Promise}
     */
    function getElementRect(el) {
      return new Promise(resolve => {
        const element = el.cloneNode(true);
        element.style.visibility = "hidden";
        element.style.position = "absolute";
        document.body.appendChild(element);
    
        resolve(element.getBoundingClientRect());
        element.remove();
      });
    }
    
    const div = /** @type {!HTMLElement} */ (document.createElement("div"));
    div.innerHTML = "

    Hello


    "; // Execute (async () => { const rect = await getElementRect(div); console.log(rect.width); })();

    DEMO

提交回复
热议问题