首页 > 解决方案 > 是否可以仅通过 CSS 将子元素移动到父元素上?

问题描述

这是我的代码:

function go(){
    let container=document.getElementById("container");
  let selector=document.getElementById("selector");
  let domRect = container.getBoundingClientRect();
  selector.style.bottom=domRect.height+"px";
  /*
  selector.style.top=domRect.height+"px";
  */
  console.log(domRect.toJSON());  
}
.container,
.result,
.selector{
  display:inline;   
  position:relative;  
}
.selector{
  background-color:red;
  left:0;
  position:absolute;
  z-index:10;
}
<table width="70%" className="bb" border="1">
  <tbody>
    <tr>
      <td>Name</td>
      <td>Chan Tai Man</td>
    </tr>
    <tr>
      <td>Date of Birth</td>
      <td>
        <div class="container" id="container">
          <div class="result" id="result">1</div>
          <div class="selector" id="selector">2</div>
        </div><button onclick="go()">Go</button>
      </td>
    </tr>
    <tr>
      <td>gg</td>
      <td>
        <button>Go</button>
      </td>
    </tr>
    <tr>
      <td>Sex</td>
      <td>Male</td>
    </tr>
  </tbody>
</table>

当我单击go按钮时,selector图层将移动到container.

  1. 我想知道,是否可以仅通过 CSS 将子元素移动到父元素上?
  2. 为什么以下代码有效?

选择器.style.bottom=domRect.height+"px";

如果我将其更改为以下内容,则它不起作用

选择器.style.bottom=domRect.top+"px";

标签: javascripthtmlcss

解决方案


恐怕这在 CSS 中根本不可能。您必须按照您希望的方式在 JS 中重新创建 html 元素。如果你想这样做,你可以使用 JS 方法,例如document.createElement() parent.removeChild('childName')element.appendChild()。也许以下步骤会有所帮助

  • 您可以复制子元素
  • 从父元素或容器元素中移除它
  • 获取您从父元素复制的元素并将其附加到父元素的父元素(<td>在这种情况下)

推荐阅读