js编写一个简单的产品放大效果代码(2)

//设置大盒子中显示的内容 var relativeX=mask.offsetLeft; var relativeY=mask.offsetTop; var proporationX=pic.offsetWidth/small.offsetWidth;      //设置比例 var proporationY=pic.offsetHeight/small.offsetWidth; pic.style.marginLeft=-relativeX*proporationX+"px";      //注意!margin的值必须是负值,“px不要丢掉 pic.style.marginTop=-relativeY*proporationY+"px";

到这一步我们的这个demo也就做完了!是不是很简单
下面我将整个代码粘贴出来,希望能和大家讨论交流。

这里是css代码 

<style> * { margin: 0; padding: 0; } #box { margin: 50px; } #small { width: 229px; height: 250px; border: 1px solid black; text-align: center; position: relative; float: left; } #mask { width: 100px; height: 100px; background-color: rgba(214, 111, 193, 0.3); position: absolute; top: 0; left: 0; /*display: none;*/ } #big { width: 350px; height: 350px; border: 1px solid black; float: left; overflow: hidden; /*display: none;*/ } </style>

这里是HTML 

<body> <div> <div> <img src="https://www.jb51.net/small_img.jpg" alt=""/> <div></div> </div> <div> <img src="https://www.jb51.net/big_img.JPG" alt=""/> </div> </div>

这里是js代码 

<script> //首先或许要操作的元素 function getId(tag){ return document.getElementById(tag) } var box=getId("box"); var small=getId("small"); var mask=getId("mask"); var big=getId("big"); var pic=big.children[0]; console.log(pic); //鼠标移动到图片上出现两个效果 small.onmouseover=function(){ mask.style.display="block"; big.style.display="block"; } small.onmouseout=function(){ mask.style.display="none"; big.style.display="none" } //设置小图的焦点框,跟随鼠标; small.onmousemove=function(e){ var marginL=box.offsetLeft; var marginT=box.offsetTop; var currentX= e.clientX; var currentY= e.clientY; var x=currentX-marginL-mask.offsetWidth/2; var y=currentY-marginT-mask.offsetHeight/2; //给焦点框设置移动区域 if(x<0){x=0;} if(x>small.offsetWidth-mask.offsetWidth){x=small.offsetWidth-mask.offsetWidth}; if(y<0){y=0;} if(y>small.offsetHeight-mask.offsetHeight){y=small.offsetHeight-mask.offsetHeight}; mask.style.left=x+"px"; mask.style.top=y+"px"; //设置大盒子中显示的内容 var relativeX=mask.offsetLeft; var relativeY=mask.offsetTop; var proporationX=pic.offsetWidth/small.offsetWidth; var proporationY=pic.offsetHeight/small.offsetWidth; pic.style.marginLeft=-relativeX*proporationX+"px"; pic.style.marginTop=-relativeY*proporationY+"px"; } </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzsdjd.html