放大镜效果之js
HTML代码:
div.box>div#left+div#buttom+div#right
div#left>img
div#buttom>div.small>img
CSS代码:
.box{ position: relative; } #left{ width:310px; height:310px; border: 1px solid blueviolet; } #buttom{ width: 310px; height: 40px; margin-top: 10px; } #buttom .small{ border: 1px solid wheat; float: left; margin-right: 5px; } #right{ width: 400px; height: 310px;; position: absolute; top:0; left:320px; border: 1px solid #ccc; display: none; overflow: hidden; } #right img{ position: absolute; top:0; left:0; }
JS代码:
1 <script> 2 function $(id){ 3 return document.getElementById(id); 4 } 5 window.onload = function () { 6 var left = $('left'); 7 var button = $('buttom'); 8 var right = $('right'); 9 button.onmouseover = function (e) { 10 var e = e||window.event;//兼容事件 11 var imgobj = e.srcElement|| e.target; //获得目标事件源,即图片 ,ie下srcElement,火狐下target 12 if(imgobj.nodeName == 'IMG'){ //当目标事件源是图片时 13 // alert(imgobj.src); 14 var names = imgobj.src; //获得图片路径 15 console.log(names); 16 console.log(names.lastIndexOf('/'));//获得/的角标位 17 console.log(names.substring(names.lastIndexOf('/'))); //从角标位开始截至最后为图片名 18 var imgOldName = names.substring(names.lastIndexOf('/')); 19 var imgNewName = imgOldName.replace('1','2'); // 从改名来换路径 20 console.log(imgNewName); 21 left.innerHTML = '<img src=img'+imgNewName +'>'; 22 } 23 }; 24 //右边图片显示逻辑 25 left.onmouseover = function () { 26 right.style.display ='block'; 27 var leftimg = left.getElementsByTagName('img')[0]; 28 var names = leftimg.src; 29 var imgoldname = names.substring(names.lastIndexOf('/')); 30 var imgNewName = imgoldname.replace('2','3'); 31 right.innerHTML = "<img src=img"+imgNewName+">"; 32 var rightImg = right.getElementsByTagName('img')[0]; 33 //添加移动事件 34 this.onmousemove = function (e) { 35 var e = e||window.event; 36 var l = e.offsetX|| e.layerX; //相对于事件源位置的兼容写法 37 var r = e.offsetY|| e.layerY; 38 //根据比例来定位大图坐标 39 rightImg.style.left = l/left.offsetWidth*(right.offsetWidth-rightImg.offsetWidth)+"px"; 40 rightImg.style.top = r/left.offsetHeight*(right.offsetHeight-rightImg.offsetHeight)+"px"; 41 } 42 } 43 //离开事件 44 left.onmouseout = function () { 45 right.style.display = 'none'; 46 } 47 } 48 </script>