使用鼠标光标更改元素位置

时间:2020-02-10 13:36:54

标签: javascript

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函数和下一个创建的元素?

1 个答案:

答案 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>