获取html字符串中指定元素的宽高的方法

111 阅读1分钟

由于html字符串还未在浏览器中渲染,即使将其转换为dom对象去调用clientWidth、clientHeight等方法,返回的结果也是0。而借助一个临时的iframe对象,将html字符串放入其中,则可以获取其长宽等信息。

 const htmlString=`
        <div style="width:300px;">
        </div>
        `
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(htmlString, 'text/html');
const iframe= document.createElement("iframe");
iframe.style.width='800px'
document.body.appendChild(iframe);
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(htmlDoc.body.innerHTML);
iframe.contentWindow.document.close();
let divNode=iframe.contentWindow.document.getElementsByTagName('div')[0]
let divNodeClientWidth=divNode.clientWidth
document.body.removeChild(iframe)
console.log(divNodeClientWidth) //300