所需要的图片
根据鼠标的方向改变图片的背景定位,实现头像始终看向鼠标
css
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 800px;
margin: 200px auto;
padding: 0 50px;
height: 500px;
box-sizing: border-box;
display: flex;
}
div {
width: 86px;
height: 86px;
background-repeat: no-repeat;
cursor: pointer;
margin: 50px;
}
.list1 {
background-image: url(./img/1.jpg);
background-position-x: -172px;
}
.list2 {
background-image: url(./img/2.jpg);
background-position-x: -172px;
}
.list3 {
background-image: url(./img/3.jpg);
background-position-x: -172px;
}
</style>
html
<div class="box">
<div class="list2">
</div>
<div class="list1">
</div>
<div class="list3">
</div>
</div>
js 部分 需要判断鼠标的方向,本人是初学者,方法比较笨还请见谅
<script>
let list = document.querySelectorAll('.box div')
let hzk = 86;
for (let i = 0; i < list.length; i++) {
list[i].onclick = function() {
for (let j = 0; j < list.length; j++) {
list[j].style.backgroundPositionX = -hzk * 8 + 'px'
}
this.style.backgroundPositionX = 0 + 'px'
}
}
window.onmousemove = function(e) {
var e = e || event;
let mouse_x = e.pageX;
let mouse_y = e.pageY;
for (let i = 0; i < list.length; i++) {
let l = list[i].offsetLeft;
let t = list[i].offsetTop;
let w = list[i].offsetWidth;
let h = list[i].offsetHeight;
//左上
if (mouse_x < l && mouse_y < t) {
list[i].style.backgroundPositionX = -hzk * 6 + 'px'
}
//左下
if (mouse_x < l && mouse_y > t + h) {
list[i].style.backgroundPositionX = -hzk * 9 + 'px'
}
//左中
if (mouse_x < l && t + h > mouse_y && mouse_y > t) {
list[i].style.backgroundPositionX = -hzk * 10 + 'px'
}
//中
if (l < mouse_x && mouse_x < l + w && mouse_y > t) {
list[i].style.backgroundPositionX = -hzk * 1 + 'px'
}
//上
if (l < mouse_x && mouse_x < l + w && mouse_y < t) {
list[i].style.backgroundPositionX = -hzk * 5 + 'px'
}
//下
if (l < mouse_x && mouse_x < l + w && mouse_y > t + h) {
list[i].style.backgroundPositionX = -hzk * 8 + 'px'
}
//右上
if (mouse_x > l + w && mouse_y < t + h) {
list[i].style.backgroundPositionX = -hzk * 4 + 'px'
}
//右下
if (mouse_x > l + w && t < mouse_y && mouse_y > t + h) {
list[i].style.backgroundPositionX = -hzk * 7 + 'px'
}
//右中
if (mouse_x > l + w && t < mouse_y && mouse_y < t + h) {
list[i].style.backgroundPositionX = -hzk * 3 + 'px'
}
// console.log(mouse_x > l + w && t < mouse_y && mouse_y < t + h);
}
}
</script>