简体   繁体   English

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

[英]Change the elements position with the mouse cursor

 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>

With the code above i want to apply the moveMouse function on all elements which i create by clicking.使用上面的代码,我想在我通过单击创建的所有元素上应用moveMouse函数。 Now that function is working only for the first element ( the div with the class .square );现在该函数仅适用于第一个元素(具有.square类的div ); How to apply the moveMouse function and for the next created elements by clicking?如何通过单击应用moveMouse功能和下一个创建的元素?

Use querySelectorAll and loop through the elemtns to change their position :使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM