在div javascript中的一些特定像素之后的appendchild

时间:2018-06-15 03:47:39

标签: javascript html dom

我想在一些特定的像素之后在另一个div中追加一个div。例如,首先,我创建了一个Div而不是用offsetHeight来计算它的高度。现在我想在中间追加一个Div Inside父Div(父亲div高度的一半)



var ts = document.querySelectorAll('article')[0];
var ks = ts.offsetHeight;
var lirf = ks/2;

<article>Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
</article>
&#13;
&#13;
&#13; 想要在上面的代码

lirf px追加儿童

查找答案关闭够了

当我使用绝对位置时,我的div重叠,如下面的代码所示:

&#13;
&#13;
<div id='get' style=''>kad</div>
<article >Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
Giving some Height to it.<br/>
</article>
<script>
var ts = document.querySelectorAll('article')[0];
var ks = ts.offsetHeight;
var lirf = ks/2;
var kk = document.getElementById('get');
kk.style.position = "absolute";
kk.style.top=lirf+'px';
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

var ts = document.querySelectorAll('article')[0];
var ks = ts.offsetHeight;
var lirf = ks/2;


var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.position = 'absolute';
div.style.top= lirf+'px';
document.querySelectorAll('article')[0].appendChild(div);

希望这有帮助!

如果您的目标是垂直居中,请完成此https://vanseodesign.com/css/vertical-centering/