我有一个网页的代码,我不能改变它是这样设置的:
<table style="width: 750px; margin-left: auto; margin-right: auto">
<tr>
<td>
<table>
<tr><td><div id=1></td></tr>
<tr><td><div id=2></td></tr>
<tr><td><div id=3></td></tr>
<tr><td><div id=4></td></tr>
</table>
</td>
</tr>
</table>我想在外部表的右边添加一个元素(通过用户脚本),它与div 1、2、3或4对齐。有什么方法可以做到这一点吗?也许可以测量元素的当前位置,然后相对于外部表的绝对位置?
(实际的HTML要混乱得多;还有更多的兄弟节点和父节点,但这是代码的核心。)
发布于 2020-08-05 03:43:40
将元素放置在表行附近
创建所需的元素并将其附加到表中。然后创建并添加反映表格行位置的自定义样式。我已经在下面写下了一些注释,以帮助导航代码。
// Setup additional element
const yourContent = document.createElement("div");
yourContent.setAttribute("class", "content");
const yourText = document.createTextNode("Lorem ipsum");
yourContent.appendChild(yourText);
// Find the element you would like to attach to
const graphElem = document.getElementsByClassName("rows");
// Set the styles to be added
const cssTemplateString = `td > .rows > .content{
position: absolute;
left: ${graphElem[0].clientWidth}px; // For element to appear on the left side set to "-" ( negative value )
height: calc(${graphElem[0].clientHeight}px +2px); // The 2 extra pixels are for the border
width: calc(${graphElem[0].clientWidth}px + 2px);
background: white;
padding: 3rem;
border: 1px solid gray;
top: 0;
}`;
const styleTag = document.createElement("style");
styleTag.innerHTML = cssTemplateString;
// Add styles to the head tag
document.head.insertAdjacentElement("beforeend", styleTag);
// Only required for this example
for (let i = 0; i < graphElem.length; i++) {
graphElem[i].addEventListener("click", function (event) {
event.target.appendChild(yourContent);
});
}td > .rows {
border: 1px solid gray;
width: 8rem;
padding: 3rem;
background: whitesmoke;
}
td {
position: relative; /* The additional content will be positioned relative to this */
}演示:https://jsfiddle.net/hexzero/82bpaL4e/
在演示中,如果您单击表行,则内容将出现在右侧。
https://stackoverflow.com/questions/63252632
复制相似问题