【发布时间】:2022-02-10 08:28:15
【问题描述】:
我有这个sn-p。 我有一个 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>
【问题讨论】:
标签: javascript html css