代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<script type="text/javascript" src="js/common.js"></script>
<style type="text/css">
body,div,img{padding:0;margin:0;}
#main{
margin:50px;
position:relative; }
#small{
width:300px;
height:187px;
border:1px solid red; } #small img{
width:300px;
height:187px;
}
#small #mark{
width:50px;
height:50px;
background-color: #ccc;
opacity:0.5;
position:absolute;
top:0px;
left:0px;
display:none;
}
#big{
width:300px;
height:187px;
border:1px solid red;
position:absolute;
top:0px;
left:320px;
overflow:hidden;
display:none;
}
/*图片想要移动必须绝对定位*/
#big img {
position:absolute;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oSmall = $('small');
var oBig = $('big');
var oMark = $('mark');
var bigImg = oBig.getElementsByTagName('img')[0]; oSmall.onmouseover = function(){
oMark.style.display = 'block';
oBig.style.display = 'block';
} oSmall.onmouseout = function(){
oMark.style.display = 'none';
oBig.style.display = 'none';
} oSmall.onmousemove = function(e){
var ev = e || window.event; //鼠标在small小图里面的距离
var x = ev.clientX - oSmall.parentNode.offsetLeft;
var y = ev.clientY - oSmall.parentNode.offsetTop; //确定镜头的坐标
var markLeft = x - (mark.offsetWidth/2);
var markTop = y - (mark.offsetHeight/2); //控制镜头边界
//如果距离左边小于0,就重新赋值为0
if (markLeft < 0) {
markLeft = 0;
}
//如果距离顶部小于0,就重新赋值为0
if (markTop < 0) {
markTop = 0;
}
//如果镜头的右边移动的距离加上本身的宽度大于small小图的宽度,说明右边过界了
if (markLeft+oMark.offsetWidth > oSmall.offsetWidth) {
markLeft = oSmall.offsetWidth - oMark.offsetWidth;
} //如果镜头的下面移动的距离加上本身的高度大于small小图的高度,说明底部过界了
if (markTop+oMark.offsetHeight > oSmall.offsetHeight) {
markTop = oSmall.offsetHeight - oMark.offsetHeight;
}
//设置镜头的位置
oMark.style.left = markLeft + 'px';
oMark.style.top = markTop + 'px'; //计算大图移动的比例算法
//markLeft/(oSmall.offsetWidth-oMark.offsetWidth) ==
//bigLeft/(bigImg.offsetWidth-big.offsetWidth)
//
var bigLeft = markLeft/(oSmall.offsetWidth-oMark.offsetWidth) * (bigImg.offsetWidth-big.offsetWidth);
var bigTop = markTop/(oSmall.offsetHeight-oMark.offsetHeight) * (bigImg.offsetHeight-big.offsetHeight); bigImg.style.left = -bigLeft + 'px';
bigImg.style.top = -bigTop + 'px';
}
}
</script>
</head>
<body>
<div id="main">
<div id="small">
<img src="img/ktm_small.jpg" alt="">
<div id="mark"></div>
</div>
<div id="big">
<img src="img/ktm_big.jpg" alt="">
</div>
</div>
</body>
</html>