简体   繁体   English

Javascript 鼠标移动事件

[英]Javascript mousemove event

I have this snippet.我有这个片段。 I have the div bar on which I act with a listener for the mousemove event.我有一个 div 栏,我在该栏上与 mousemove 事件的侦听器一起使用。 Depending on the coordinates of the mouse, the hello elements move on the x-axis.根据鼠标的坐标,hello 元素在 x 轴上移动。

How can I, when the mouse is no longer on the bar, that is, outside, the hello elements in the bar, return to the initial position?当鼠标不再在栏上时,即在栏外,栏中的hello元素,如何返回初始的position? For example, while the mouse is over the bar, the hello elements move to the right, and when the mouse is no longer on the bar, they return to their original position.例如,当鼠标悬停在栏上时,hello 元素向右移动,当鼠标不再位于栏上时,它们会返回到原来的 position。

 const bar = document.querySelector('.bar'); const layer = document.querySelectorAll('.layer'); const eff = function(mouse) { layer.forEach(layer => { const x = (window.innerWidth - mouse.pageX) / 10; const y = (window.innerHeight - mouse.pageY) / 10; layer.style.transform = `translateX(${x}px)translateY(${y}px)`; }) }; bar.addEventListener('mousemove', eff);
 * { margin: 0; padding: 0; box-sizing: border-box; }.bar { height: 20vh; background: black; position: relative; display: flex; align-items: center; justify-content: space-around; } #red { color: red; } #blue { color: blue; }
 <div class="bar"> <div class="hello"> <h2 id='red' class='layer'>Hello</h2> <h2 id='blue' class='layer'>Hello</h2> </div> </div>

You can add another listener for the mouseleave event and then simply reset the translation to 0px for each layer.您可以为mouseleave事件添加另一个侦听器,然后简单地将每一层的平移重置为0px

 const bar = document.querySelector('.bar'); const layer = document.querySelectorAll('.layer'); const eff = function(mouse) { layer.forEach(layer => { const x = (window.innerWidth - mouse.pageX) / 10; const y = (window.innerHeight - mouse.pageY) / 10; layer.style.transform = `translateX(${x}px)translateY(${y}px)`; }) }; const reset = function(mouse) { layer.forEach(layer => { layer.style.transform = `translateX(0px)translateY(0px)`; }) }; bar.addEventListener('mousemove', eff); bar.addEventListener('mouseleave', reset);
 * { margin: 0; padding: 0; box-sizing: border-box; }.bar { height: 20vh; background: black; position: relative; display: flex; align-items: center; justify-content: space-around; } #red { color: red; } #blue { color: blue; }
 <div class="bar"> <div class="hello"> <h2 id='red' class='layer'>Hello</h2> <h2 id='blue' class='layer'>Hello</h2> </div> </div>

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

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