首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将元素定位在包含元素之外

将元素定位在包含元素之外
EN

Stack Overflow用户
提问于 2020-08-05 01:59:36
回答 1查看 241关注 0票数 0

我有一个网页的代码,我不能改变它是这样设置的:

代码语言:javascript
复制
<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要混乱得多;还有更多的兄弟节点和父节点,但这是代码的核心。)

EN

回答 1

Stack Overflow用户

发布于 2020-08-05 03:43:40

将元素放置在表行附近

创建所需的元素并将其附加到表中。然后创建并添加反映表格行位置的自定义样式。我已经在下面写下了一些注释,以帮助导航代码。

代码语言:javascript
复制
// 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);
  });
}
代码语言:javascript
复制
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/

在演示中,如果您单击表行,则内容将出现在右侧。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63252632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档