document.addEventListener('mousemove', moveMouse)
function moveMouse(params) {
const clientX = params.clientX;
const clientY = params.clientY;
const square = document.querySelector('.square');
square.style.left = clientX + 'px';
square.style.top = clientY + 'px';
}
document.addEventListener('click', function() {
const p = document.createElement("div");
p.classList.add('square');
const container = document.querySelector('.container');
container.appendChild(p);
})
.square {
border: 2px solid black;
width: 25px;
height: 25px;
display: block;
background-color: blanchedalmond;
border-radius: 50%;
position: relative;
transform: translate(-72%,-72%);
opacity: 0.3;
}
<div class="container">
<div class="square"></div>
</div>
使用上面的代码,我想在单击创建的所有元素上应用moveMouse
函数。现在,该功能仅适用于第一个元素(类为div
的{{1}});如何通过单击来应用.square
函数和下一个创建的元素?
答案 0 :(得分:1)
使用querySelectorAll
并遍历元素以更改其位置:
document.addEventListener('mousemove', moveMouse)
function moveMouse(params) {
const clientX = params.clientX;
const clientY = params.clientY;
const squares = document.querySelectorAll('.square');
squares.forEach(sq => {
sq.style.left = clientX + 'px';
sq.style.top = clientY + 'px';
});
}
document.addEventListener('click', function() {
const p = document.createElement("div");
p.classList.add('square');
const container = document.querySelector('.container');
container.appendChild(p);
})
.square {
border: 2px solid black;
width: 25px;
height: 25px;
display: block;
background-color: blanchedalmond;
border-radius: 50%;
position: relative;
transform: translate(-72%,-72%);
opacity: 0.3;
}
<div class="container">
<div class="square"></div>
</div>