圖片放大鏡效果
阿新 • • 發佈:2018-09-28
分享 圖片 div lock bubuko 技術 mouseout fun play
類似某寶的圖片放大鏡效果,言簡意賅,直接上代碼
html
<div id="container"> <div class="leftView"> <div class="mask"></div> <img class="smallImg" src="./5.jpg" alt="縮小版"> </div> <div class="rightView"> <img class="bigImg"src="./5.jpg" alt="放大版"> </div> </div>
css
#container { position: relative; } .leftView { position: relative; width: 318px; height: 318px; } .smallImg { max-height: 100%; max-width: 100%; } .mask { display: none; position: absolute; background: pink; /* width: 100px; height: 100px; top:0; left: 0; */ opacity: 0.5; /* background: url(./images/5.jpg); */ cursor: move; } .bigImg{ position: absolute; width: 400px; height: 400px; } .rightView { display: none; position: absolute; left: 338px; top: 0; width: 318px; height: 318px; overflow: hidden; }
js
function calculateMaskWH() { var width = $(‘.leftView‘).width() / $(‘.bigImg‘).width() * $(‘.rightView‘).width(); var height = $(‘.leftView‘).height() / $(‘.bigImg‘).height() * $(‘.rightView‘).height(); $(‘.mask‘).css({ width: width, height: height }); // console.log($(‘.mask‘).width(),$(‘.mask‘).height()); } calculateMaskWH(); //監聽鼠標mouseover事件 $(‘.leftView‘).on(‘mouseover‘, function () { $(‘.mask‘).css(‘display‘, ‘block‘); $(‘.rightView‘).css(‘display‘, ‘block‘); $(‘.leftView‘).on(‘mousemove‘, function (event) { //計算放大鏡的left值和top值 var left = event.pageX - $(this).offset().left - $(‘.mask‘).width() / 2; var top = event.pageY - $(this).offset().top - $(‘.mask‘).height() / 2; //判斷放大鏡左右是否出界 if (left< 0) { left = 0 } else if (left > $(this).width() - $(‘.mask‘).width()) { left = $(this).width() - $(‘.mask‘).width(); } //判斷放大鏡上下是否出現 if (top < 0) { top = 0; } else if (top > $(this).height() - $(‘.mask‘).height()) { top = $(this).height() - $(‘.mask‘).height(); } $(‘.mask‘).css({ left: left + ‘px‘, top: top + ‘px‘ }); //計算比例 var rate = $(‘.bigImg‘).width() / $(‘.leftView‘).width(); $(‘.bigImg‘).css({ left: -rate * left + ‘px‘, top: -rate * top + ‘px‘ }); }); }); //監聽鼠標mouseout事件 $(‘.leftView‘).on(‘mouseout‘, function () { $(‘.mask‘).css(‘display‘, ‘none‘); $(‘.rightView‘).css(‘display‘, ‘none‘); });
運行結果:
喜歡粉粉的哈哈哈~
代碼地址:https://github.com/ouxiaojie18/-/tree/master/%E6%94%BE%E5%A4%A7%E9%95%9C%E6%95%88%E6%9E%9C
圖片放大鏡效果