我想要获取HTML元素及其所有计算样式。
当HTML元素没有子元素时,我已经成功实现了这个功能,但如果HTML元素有许多子元素,我该如何获取每个子元素的所有计算样式?
以下是我目前拥有的:
- 用户点击HTML元素后,我使用event.target.cloneNode(true)获取HTML元素
- 然后我为克隆的元素设置一个ID
- 我获取计算样式
- 然后将样式添加到我的克隆元素中
private onClickHtmlCssGrabber = (event) => {
// clone the html element
let clickedHtmlElement = event.target.cloneNode(true)
// set an id to the cloned element
clickedHtmlElement.setAttribute('id', 'clonedElement')
// get the computed style of the element
let clikedHtmlElementStyle = getComputedStyle(event.target).cssText
// set the style on my newly cloned element
clickedHtmlElement.style.cssText = clikedHtmlElementStyle
}
所以基本上,此时我最终得到的东西类似于:
<div id="clonedElement" style="... all the coputedStyle">Example text</div>
但当我想要提取的HTML元素有很多子元素时,我的问题就出现了:
<div class="style1">
<div class="style-child-1">
<div class="style-child-2">
example text child 2
<div>
<div class="style-child-3">
example text child 3
</div>
<div>
</div>
那么我如何提取整个带有其子元素及其样式的HTML元素?