css部分
<style type="text/css">
*{
margin:0;
padding:0;
}
.bigbox{
width:1000px;
margin:0 auto;
}
.left{
width:400px;
height:400px;
position:relative;
float:left;
border:1px solid black;
}
.left img{
width:400px;
height:400px;
position:absolute;
}
.right{
width:500px;
height:500px;
float:left;
position:relative;
border:1px solid black;
overflow:hidden;
}
.right img{
width:800px;
height:800px;
position:absolute;
}
.moves{
width:250px;
height:250px;
background:pink;
position:absolute;
z-index: 2;
opacity:0.3;
}
</style>
html部分
<div class="bigbox">
<div class="left" id="leftbox">
<img src="xie.jpg" alt="" />
<div class="moves" id="move"></div>
</div>
<div class="right" id="rightbox">
<img src="xie.jpg"alt="" id="rightimg" />
</div>
</div>
js部分
<script type="text/javascript">
leftbox.onmouseover=function(){ //鼠标悬停时
move.style.display="block"; //先让可移动的方块和右边的盒子出现
rightbox.style.display="block";
}
leftbox.onmouseout=function(){ //鼠标移出时
move.style.display="none"; //让可移动的方块和右边的盒子隐藏
rightbox.style.display="none";
}
moves.onmousemove=function(e){ //可移动的盒子移动时发生的函数
var e=e||event;
var x=e.clientX-leftbox.offsetLeft-moves.offsetWidth/2; //算出鼠标在左边盒子里距左的位置
var y=e.clientY-leftbox.offsetTop-moves.offsetHeight/2; //算出鼠标在左边盒子里距上的位置
if(x<0){
x=0;
}
if(y<0){
y=0;
}
if(x>leftbox.offsetWidth-moves.offsetWidth){
x=leftbox.offsetWidth-moves.offsetWidth
}
if(y>leftbox.offsetHeight-moves.offsetHeight){
y=leftbox.offsetHeight-moves.offsetHeight
}
moves.style.top=y+"px";
moves.style.left=x+"px";
rightimg.style.top=-y*2+"px";
rightimg.style.left=-x*2+"px";
}
</script>
jq部分
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
$(".left").hover(
function(){
$(".moves").css("display","block");
$(".right").css("display","block");
},
function(){
$(".moves").css("display","none");
$(".right").css("display","none");
}
)
$(".moves").mousemove(function(e){
var e=e||event;
var x=e.clientX-$(".left").offset().left-$(".moves").width()/2;
var y=e.clientY-$(".left").offset().top-$(".moves").height()/2;
if(x<0){
x=0;
}
if(y<0){
y=0;
}
if(x>$(".left").width()-$(".moves").width()){
x=$(".left").width()-$(".moves").width();
}
if(y>$(".left").height()-$(".moves").height()){
y=$(".left").height()-$(".moves").height();
}
$(".moves").css({"left":(x)+'px',"top":(y)+'px'});
$(".rightimg").css({"left":(-x*2)+'px',"top":(-y*2)+'px'});
})
})
用到的知识点:
js:
1.onmouseover 鼠标悬停
2.onmouseout 鼠标移出
3.onmouseomove 鼠标移动
4.clientX 鼠标在页面中的水平坐标
5.clientY 鼠标在页面中的垂直坐标
6.offsetWidth 返回元素可见宽度
7.offsethHeight 返回元素可见高度
jq:
1.hover