18910140161

JavaScript-是否可以仅通过CSS移动父元素上的子元素?-堆栈溢出

顺晟科技

2022-10-18 12:23:57

103

这是我的代码:

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 ”>;<;正文(>;)<;TR>;<;TD>;名称<;/TD>;<;TD>;陈大文<;/TD>;<;/tr>;<;TR>;<;TD>;出生日期<;/TD>;<;TD>;<;DIV类=“容器” ID=“容器”>;<;DIV类=“结果” ID=“结果”>;1<;/DIV>;<;DIV类=“选择器” ID=“选择器”>;2<;/DIV>;<;/DIV>;<;button onclick=“ go()”>;go<;/button>;<;/TD>;<;/tr>;<;TR>;<;TD>;gg<;/TD>;<;TD>;<;按钮>;转到<;/按钮>;<;/TD>;<;/tr>;<;TR>;<;TD>;性别<;/TD>;<;TD>;男性<;/TD>;<;/tr>;<;/t正文>;<;/表格>;

当我单击<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的上方。

  1. 我想知道,是否可以只通过CSS移动父元素上的子元素?
  2. 为什么下面的代码工作?
<块引用>

selector.style.bottom=domRect.height+";px";

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

<块引用>

selector.style.bottom=domRect.top+";px";


顺晟科技:

恐怕这在CSS中是不可能的。您必须在JS中按照您希望的方式重新创建HTML元素。如果您想这样做,您可以使用JS方法,如containerdocument.createElement()parent.removeChild('childName')

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航