您好,登錄后才能下訂單哦!
本文實例為大家分享了js實現放大鏡特效的具體代碼,供大家參考,具體內容如下
掌握頁面元素定位和移動
放大鏡關鍵原理:鼠標在小圖片上移動時,通過捕捉鼠標在小圖片上的位置定位大圖片的相應位置
技術點:事件捕獲、定位
offsetLeft與style.left的對比:
1)offsetLeft是與父級元素的距離,不包過滾動條的距離
2)style.left返回的是字符串,如30px,offsetLeft返回的是數值30
3)style.lft是可讀寫的,offsetLeft是只讀的,所以要改變div的位置只能修改style.left
4)style.left的值需要事先定義,否則取到的值為空
難點:計算:如何讓小圖片的放大鏡和大圖片同步移動
距離定位圖解:
具體代碼:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <style type="text/css"> *{ margin: 0; padding: 0; } #demo{ display: block; width: 400px; height: 255px; margin: 50px; position: relative; border: 1px solid #ccc; } #small-box{ position: relative; z-index: 1; } #float-box{ display: none; width: 160px; height: 120px; position: absolute; background: #ffffcc; border: 1px solid #ccc; filter: alpha(opacity=50); opacity: 0.5; } #mark{ position: absolute; display: block; width: 400px; height: 255px; background-color: #fff; filter: alpha(opacity=0); opacity: 0; z-index: 10; } #big-box{ display: none; position: absolute; top: 0; left: 460px; width: 400px; height: 300px; overflow: hidden; border: 1px solid #ccc; z-index: 1; } #big-box img{ position: absolute; z-index: 5; } </style> <script> window.onload=function(){ var $=function(id){ return document.getElementById(id); } var Demo = $("demo"); var SmallBox = $("small-box"); var Mark = $("mark"); var FloatBox = $("float-box"); var BigBox = $("big-box"); var BigBoxImage = BigBox.getElementsByTagName("img")[0]; Mark.onmouseover = function(){ FloatBox.style.display = "block"; BigBox.style.display = "block"; } Mark.onmouseout = function(){ FloatBox.style.display = "none"; BigBox.style.display = "none"; } Mark.onmousemove = function(e){ var _event = e||window.event//兼容多個瀏覽器的參數模式 var left = _event.clientX - Demo.offsetLeft - SmallBox.offsetLeft - FloatBox.offsetWidth/2; var top = _event.clientY - Demo.offsetTop - SmallBox.offsetTop - FloatBox.offsetHeight/2; if(left < 0){ left = 0; }else if(left > Mark.offsetWidth - FloatBox.offsetWidth){ left = Mark.offsetWidth - FloatBox.offsetWidth; } if(top < 0){ top = 0; }else if(top > Mark.offsetHeight - FloatBox.offsetHeight){ top = Mark.offsetHeight - FloatBox.offsetHeight; } FloatBox.style.left = left + 'px'; FloatBox.style.top = top + 'px'; var percentX = left / (Mark.offsetWidth - FloatBox.offsetWidth); var percentY = top / (Mark.offsetHeight - FloatBox.offsetHeight); BigBoxImage.style.left = -percentX * (BigBoxImage.offsetWidth - BigBox.offsetWidth)+'px'; BigBoxImage.style.top = -percentY * (BigBoxImage.offsetHeight - BigBox.offsetHeight)+'px'; } } </script> <body> <div id="demo"> <div id="small-box"> <div id="mark"></div> <div id="float-box"></div> <img src="img/macbook-small.jpg" /> </div> <div id="big-box"> <img src="img/macbook-big.jpg" /> </div> </div> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。