今天我想写一个放大镜因为毕竟在做网页的时候,特别是一些电商的详情页放大镜是必不可少的.什么都不说了上代码
1,html代码
<div id='small'><img src="2.jpg" alt="" width='100%'><div id='move'></div></div>
<ul id="images">
<li><img class="imgs" src="2.jpg" alt="" width="100%"></li>
<li><img class="imgs" src="3.jpg" alt="" width="100%"></li>
<li><img class="imgs" src="4.jpg" alt="" width="100%"></li> </ul>
<div id='big'><img src="2.jpg" alt="" id='img'></div>
2,css代码
<style>
*{margin:;padding:;list-style: none; }
#small{width:400px;height:400px;border:1px solid black;position: absolute;left:50px;top:50px;}
#move{width:100px;height:100px;position:absolute;left:;top:;background: url(bg.png);display: none;}
#images{position:absolute;top:460px;left:60px;width:1000px;height:100px;}
#images li { width: 80px; height: 80px; float: left; margin-right: 10px; border: solid 1px #333;padding: 4px;}
#big{width:400px;height:400px;border:1px solid black;position:absolute;left:500px;top:50px;overflow:hidden;display:none;}
#big #img{position: absolute;left:-100px;}
</style>
3,js代码
<script>
var small = document.getElementById('small');
var big = document.getElementById('big');
var move = document.getElementById('move');
var img = document.getElementById('img') //1 图片替换
var list = images.children;
// console.log(list);
for(var i=0;i<list.length;i++){
list[i].onclick = function (){
var src = this.firstElementChild.src;
//小图大图的图片资源都要替换
small.firstElementChild.src = src;
big.firstElementChild.src = src;
}
}
//2 鼠标移动
small.onmousemove = function(ent){
//大盒子显示 放大镜显示
big.style.display = "block";
move.style.display = "block"; //获得鼠标
var ent = ent || window.event; //放大镜不能出盒子范围
var minX = 0;
var maxX = small.offsetWidth-move.offsetWidth;
var minY = 0;
var maxY = small.offsetHeight-move.offsetHeight; if(ent.clientX-move.offsetWidth<minX){//e.pageX
move.style.left ="0px";
}else if(ent.clientX-move.offsetWidth>maxX){//e.pageX
move.style.left =maxX+"px";
}else{
move.style.left = (ent.clientX-move.offsetWidth)+"px";//e.pageX
} if(ent.clientY-move.offsetHeight<minY){//e.pageY
move.style.top ="0px";
}else if(ent.clientY-move.offsetHeight>maxY){//e.pageY
move.style.top =maxY+"px";
}else{
move.style.top = (ent.clientY-move.offsetHeight)+"px";//e.pageY
} //大盒子随鼠标的移动位置
big.scrollTop = (ent.clientY-small.offsetTop)*2.5-200;//e.pageY
big.scrollLeft = (ent.clientX-small.offsetLeft)*2.5-250;//e.pageX //放大镜的位置 (会出盒子范围)
// move.style.left = (ent.clientX-move.offsetWidth)+"px";
// move.style.top = (ent.clientY-move.offsetHeight)+"px"; //添加鼠标样式
small.style.cursor = "move"; }
//3 鼠标移出
small.onmouseout = function(){
//大盒子\放大镜消失
big.style.display = "none";
move.style.display = "none";
//恢复默认样式
small.style.cursor = "default";
}
</script>
原理:
只要我们算放大镜的位置,其实放大镜并不难 在这里要特别注意一点,e.clientX/clientY和e.pageX/pageY两者之间的区别,不然在做放大镜的时候会出现bug.
好了今天放大镜写到这里明天我们写jQuery放大镜.