gpt4 book ai didi

javascript - 如何在行尾添加新的子DIV?

转载 作者:行者123 更新时间:2023-11-28 17:33:20 27 4
gpt4 key购买 nike

单击子 DIV 时,查找子 DIV 在哪一行被单击,并在行末尾添加新的子 DIV。

我尝试尽我所能,但到目前为止我只能将新 child 添加到第一行。这是代码片段:

var pNode = document.querySelector('.parent');
var divs = document.querySelectorAll('.child');
var x = divs.length;

console.log(x);

var number_of_elements_in_first_row = 0;

for (var i = 0; i < x; i++) {
divs[i].addEventListener('click', function(event) {
// console.log(event.target.offsetTop)
// console.log(event.target)
var newChild = document.querySelector('.new-child');
if (newChild) {
newChild.parentElement.removeChild(newChild);
}
setTimeout(function() {
addChildToEndOfRow()
}, 200);
}, false);
}

function addChildToEndOfRow() {
for (var i = 0; i < x; i++) {
if (divs[0].offsetTop !== divs[i].offsetTop) {

var newDiv = document.createElement('div')
newDiv.innerHTML = "boom";
newDiv.classList.add("new-child");
pNode.insertBefore(newDiv, divs[i])

number_of_elements_in_first_row = i;
break;
}
}
}
.parent {
width: 380px;
}

.parent .child {
display: inline-block;
margin-right: 2px;
background-color: gray;
margin-bottom: 20px;
padding: 0 10px
}

.parent .new-child {
background-color: rgba(0, 0, 0, .2);
margin-bottom: 20px;
}
<div class="parent">
<div class="child">1234</div>
<div class="child">12341234 </div>
<div class="child">123412341234</div>
<div class="child">1234</div>
<div class="child">12341234</div>
<div class="child">123412341234</div>
<div class="child">1234</div>
<div class="child">12341234</div>
<div class="child">123412341234</div>
</div>

这是jsfiddle 。只需要纯 Javascript 解决方案。提前致谢。

最佳答案

试试这个代码:

var pNode = document.querySelector('.parent');
var divs = document.querySelectorAll('.child'); //or

var x = divs.length;

console.log(x);

var number_of_elements_in_first_row = 0;

for (var i = 0; i < x; i++) {
divs[i].addEventListener('click', function(event) {
var newChild = document.querySelector('.new-child');
if (newChild) {
newChild.parentElement.removeChild(newChild);
}
setTimeout(function() {
addChildToEndOfRow(event.target.offsetTop);
}, 200);
}, false);
}

function addChildToEndOfRow(offsetTop) {
var newDiv = document.createElement('div')
newDiv.innerHTML = "boom";
newDiv.classList.add("new-child");
var addAfterOffsetTop;
for (var i = 0; i < x; i++) {
if (addAfterOffsetTop && divs[i].offsetTop > addAfterOffsetTop) {
pNode.insertBefore(newDiv, divs[i]);
return;
}
if (offsetTop === divs[i].offsetTop) {
addAfterOffsetTop = divs[i].offsetTop;
}
}

pNode.appendChild(newDiv, divs[divs.length-1]);
}

关于javascript - 如何在行尾添加新的子DIV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49794456/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com