<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #imgBox{width: 180px;height: 180px;overflow: hidden;position: relative;margin:40px;background: #ccc;;} #imgBox span{ border:2px solid #bbb;box-sizing: border-box; width: 80px;height: 80px;position: absolute;left: 0;top: 0; background:#ccc;filter: alpha(opacity=50); opacity: 0.4;display: none; } #imgInfo{ display: none; width: 400px;height: 400px;position: absolute;left:240px;top: 80px;overflow: hidden; } #imgInfo img{ position: absolute;left: 0px;top: 0px;} #mark{position:absolute;width: 180px;height: 180px;left: 0px;top:0px;opacity: 0;filter: alpha(opacity=100);background:lawngreen;} </style> </head> <body> <div id='imgBox'> <img src="img/b2.jpg" alt="商品小图"></img> <span></span> <mark id="mark"></mark> </div> <div id="imgInfo"> <img src="img/b1.jpg" alt="细节图片"/> </div> <script> window.onload = function() { var imgBox = document.getElementById('imgBox'); var span = imgBox.getElementsByTagName('span')[0]; var boxInfo=document.getElementById('imgInfo'); var imgInfo=boxInfo.getElementsByTagName('img')[0]; imgBox.onmouseover = function() { span.style.display = 'block'; boxInfo.style.display='block'; } imgBox.onmouseout = function() { span.style.display = "none"; boxInfo.style.display='none'; } imgBox.onmousemove = function(ev) { var boxL = imgBox.offsetLeft; var boxT=imgBox.offsetTop; var ev = ev || window.event; var boxW=imgBox.offsetWidth; var boxH=imgBox.offsetHeight; var spanW = span.offsetWidth; var spanH = span.offsetHeight; var spanL=ev.clientX-boxL-(spanW / 2); var spanT=ev.clientY - (spanH / 2) -boxT; imgBox.style.cursor='pointer'; if(spanL<0) { spanL=0; }else if(spanL>boxW-spanW){ spanL=boxW-spanW; } if(spanT<0) { spanT=0; } else if(spanT>boxH-spanH){ spanT=boxH-spanH; }else{ span.style.left = spanL+ 'px'; span.style.top = spanT+ 'px'; var scaleX=spanL/(boxW-spanW); var scaleY=spanT/(boxH-spanH); imgInfo.style.left=-scaleX*(imgInfo.offsetWidth-boxInfo.offsetWidth)+'px'; imgInfo.style.top=-scaleY*(imgInfo.offsetHeight-boxInfo.offsetHeight)+'px'; } } // 子元素影响父元素的解决方案: // 1.JS解决方案:onmouseenter;onmouseleave; // 效果和onmouseover,onmouseout是一样的但是子元素不会影响父元素 // 2.css解决方案:加一个层Mark; /*function elContains(a, b) { return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition(b) & 16); } imgBox.onmouseover = function(ev) { var ev = ev || window.event; var a = this, b = ev.relatedTarget; if (!elContains(a, b) && a != b) { document.title += 1 } } */ } </script> </body> </html>