我有这个片段。 我有一个 div 栏,我在上面与 mousemove 事件的监听器一起操作。根据鼠标的坐标,hello 元素在 x 轴上移动。
当鼠标不再位于栏上,即不在栏内的 hello 元素上时,如何返回到初始位置? 例如,当鼠标位于栏上时,hello 元素会向右移动,当鼠标不再位于栏上时,它们会返回到原始位置。
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>
最佳答案
您可以为 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>
关于JavaScript 鼠标移动事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71053813/