HTML
<div class="shell">
设置一个div
</div>
css
.shell{
width: 300px;
height: 170px;
background-image: url("xxx.jpg"); // 背景图片
background-repeat: no-repeat; // 重复/不重复
background-position: 0px -90px; // 图片定位
(主要利用这个属性,来实现鼠标移动比例比图片移动比例小)
}
js
const shell = document.querySelector('.shell') // 获取dom
shell.addEventListener('mouseenter',function(e){ // 监控移入的位置
this.x = e.clientX // 鼠标移入的位置等于图片定位位置
this.y = e.clientY
})
shell.addEventListener('mousemove',function(e){ // 监控图片里的移动
this.i = e.clientX // 监控移动位置
this.j = e.clientY
const disx = this.i - this.x // 移动位置,减去移入的位置,得到鼠标移动的距离。
const disy = this.j - this.y
const movex = disx * 2 // 根据鼠标移动的距离,更改图片定位,2代表倍率。
const movey = -90 + disy/2
shell.style.backgroundPosition=`${movex}px ${movey}px`
})
图片记得大一点,background-position图片定位属性,调整鼠标移入位置,图片复位的位置。