如图所示
代码如下:
<style>
* {
margin: 0;
padding: 0;
}
#smlImg {
width: 300px;
height: 300px;
/* position: relative; */
/* float: left; */
background-image: url(../img/2.jpg);
background-size: cover;
}
#smlDiv{
width: 100px;
height: 100px;
/* background-color: rgba(rgb(180, 175, 175), rgb(180, 175, 175), rgb(180, 175, 175), 0.5); */
background-color:rgba(212, 234, 123, 0.2);
display: none;
position: absolute;
}
#bigDiv{
width: 300px;
height: 300px;
position: absolute;
left: 300px;
top: 0px;
overflow: hidden;
display: none;
}
#bigImg{
width: 900px;
height: 900px;
position: absolute;
}
</style>
</head>
<body>
<div class="Box">
<div id="smlImg">
<div id="smlDiv" ></div>
</div>
<div id="bigDiv">
<img src="../img/2.jpg" alt="" id="bigImg">
</div>
</div>
<script>
// 鼠标移入,出现小Div和大div
var smlImg= document.getElementById('smlImg')
var smlDiv=document.getElementById('smlDiv')
var bigDiv=document.getElementById('bigDiv')
smlImg.onmouseover=function(){
smlDiv.style.display='block'
bigDiv.style.display='block'
}
// 鼠标移出,隐藏小div.大div
smlImg.onmouseout=function(){
smlDiv.style.display='none'
bigDiv.style.display='none'
}
// 小div随着鼠标移动绑定事件
smlDiv.onmousemove=function(eve){
var eve=eve||window.event
// console.log(eve)
// console.log(eve.clientX,eve.clientY)
var x=eve.clientX-50;
var y=eve.clientY-50
// 对移动范围进行判断
if(x>=200){
x=200
}
if(y>=200){
y=200
}
if(x<=0){
x=0
}
if(y<=0){
y=0
}
smlDiv.style.left=x+'px'
smlDiv.style.top=y+'px'
// 大图移动和小图相反
bigImg.style.left=-3*x+'px'
bigImg.style.top=-3*y+'px'
}
</script>
</body>
</html>
其中,需要注意的是移动的大小计算问题,需要细心一点