<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
#大边框div{
width:850px;
height:500px;
border:1px solid red;
margin:50px auto;
}
#小图{
width:350px;
height:350px;
background: url(img/small.jpg) no-repeat;
position:relative;
float:left;
}
#大图{
width:500px;
height:500px;
background: url(img/big.jpg) no-repeat;
background-position:0px 0px;
display:none;
float:left;
}
#展示块{
width:100px;
height:100px;
background:rgba(255,0,0,0.5);
position:absolute;
top:0px;
left:0px;
display:none;
}
</style>
</head>
<body>
<div id="大边框div">
<div id="小图">
<div id="展示块"></div>
</div>
<div id="大图"></div>
</div>
<script>
var 大边框div = document.getElementById('大边框div');
var 展示块 = document.getElementById('展示块');
var 小图 = document.getElementById('小图');
var 大图 = document.getElementById('大图');
小图.onmouseover=function(){
展示块.style.display='block';
大图.style.display='block';
展示块.style.cursor='move';
}
小图.onmouseout=function(){
展示块.style.display='none';
大图.style.display='none';
}
展示块.onmousedown = function(e){
var e = e || event;
var disX = e.clientX - 大边框.offsetLeft-this.offsetLeft;
var disY = e.clientY - 大边框.offsetTop-this.offsetTop;
document.onmousemove = function(e){
var e = e || event;
var oLeft = e.clientX - 大边框.offsetLeft-disX;
var oTop = e.clientY - 大边框.offsetTop-disY;
if(oLeft<=0){
oLeft=0
} else if(oLeft>=250){
oLeft=250
}
if(oTop<=0){
oTop=0
} else if(oTop>=250){
oTop=250
}
展示块.style.left= oLeft + 'px';
展示块.style.top= oTop + 'px';
var preLeft = oLeft/(小图.offsetWidth -展示框.offsetWidth);求移动的百分比
var preTop = oTop/(小图.offsetHeight-展示框.offsetHeight);求百分比
大图.style.backgroundPosition = (300*preLeft) + 'px ' + (300*preTop) + 'px';
}
document.onmouseup = function(){
document.onmousemove =null;
document.onmouseup =null;
}
}
</script>
</body>
</html>