javascript - 是否可以仅通过 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
.
- 我想知道,是否可以仅通过 CSS 将子元素移动到父元素上?
- 为什么以下代码有效?
选择器.style.bottom=domRect.height+"px";
如果我将其更改为以下内容,则它不起作用
选择器.style.bottom=domRect.top+"px";
解决方案
恐怕这在 CSS 中根本不可能。您必须按照您希望的方式在 JS 中重新创建 html 元素。如果你想这样做,你可以使用 JS 方法,例如document.createElement()
parent.removeChild('childName')
和element.appendChild()
。也许以下步骤会有所帮助
- 您可以复制子元素
- 从父元素或容器元素中移除它
- 获取您从父元素复制的元素并将其附加到父元素的父元素(
<td>
在这种情况下)
推荐阅读
- javascript - 数组和对象作为数据库
- amazon-web-services - 为 alb 创建目标组(应用程序负载均衡器)
- firebase - 如何确定 NoSQL 数据结构(更多或更少的集合)
- css - Invariant Violation: Invariant Violation: React.Children.only 期望接收单个 React 元素子元素。我不知道为什么?
- javascript - InputEvent.getTargetRanges() 总是空的?
- vue.js - 如何在 Vue 的递归组件中切换活动类?
- java - 同时向两个表中插入数据。h2 数据库
- linux - 将代码从 mac 转移到 linux 机器时出现语法错误
- angular - Angular 订阅服务:订阅不是函数
- firebase - 如果值等于 null,我不想在 firestore 上添加字段