这篇文章将为大家详细讲解有关Javascript如何模拟京东放大镜效果,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
代码如下:
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
body,div{margin: 0; padding: 0;}
#zhuti{
margin:50px;
position: relative;
}
#small{
width: 300px;
height: 187px;
border: 1px solid #000;
}
#big{
border: 1px solid #666;
overflow: hidden;
width: 300px;
height: 187px;
position: absolute;
left: 310px;
top: 0px;
display: none;
}
#jingtou{
width: 50px;
height: 50px;
background: #666;
opacity: 0.4;
position: absolute;
display: none;
}
#bigimg{
position: absolute;
}
</style>
</head>
<body>
<div id="zhuti">
<div id="small">
<div id="jingtou"></div>
<img src="img/ktm_small.jpg">
</div>
<div id="big">
<img src="img/ktm_big.jpg" id="bigimg">
</div>
</div>
<script type="text/JavaScript">
//封装一个函数(id形式参数)
function $(id) {
return document.getElementById(id);
}
var small =$('small');
var big =$('big');
var jingtou =$('jingtou');
var zhuti =$('zhuti');
var bigimg =$('bigimg');
//监视鼠标(镜头)
small.onmouseover = function(){
big.style.display='block';
jingtou.style.display='block';
}
small.onmouseout = function(){
big.style.display='none';
jingtou.style.display='none';
}
//挡鼠板移动的时候
small.onmousemove = function(event){
//获得当前坐标 //减去镜头宽度的一半
var left = event.clientX - zhuti.offsetLeft -jingtou.offsetWidth/2;
var top = event.clientY -zhuti.offsetTop - jingtou.offsetHeight/2;
//进行判断语句(固定0的位置)
//向左走
if(left<=0){
left =0;
}
//向上走
if(top<=0){
top =0;
}
//向右走
if(left >= small.offsetWidth-jingtou.offsetWidth){
left = small.offsetWidth-jingtou.offsetWidth;
}
//向下走
if(top >= small.offsetHeight-jingtou.offsetHeight){
top = small.offsetHeight-jingtou.offsetHeight;
}
//小图的比例
var smallX = left / (small.offsetWidth - jingtou.offsetWidth);
//var smallX = left / (small.offsetWidth - jingtou.offsetWidth);
var smallY = top / (small.offsetHeight - jingtou.offsetHeight);
//var smallY = top / (small.offsetHeight - jingtou.offsetHeight);
var bigX = -smallX * (bigimg.offsetWidth - big.offsetWidth);
var bigY = -smallY * (bigimg.offsetHeight - big.offsetHeight);
//求a和b的值
bigimg.style.left = bigX + 'px';
bigimg.style.top = bigY + 'px';
//镜头距离左边的位置==鼠标距离左边的位置
jingtou.style.left = left +'px';
jingtou.style.top = top +'px';
}
</script>
</body>
</html>
关于“Javascript如何模拟京东放大镜效果”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。