1. 程式人生 > >js實現放大鏡效果

js實現放大鏡效果

設置 信息 鼠標 放大 ack 視口 seo bim wid

html部分

<div id="box">
        <img width="100%" height="100%" src="images/1.png" alt="#">
        <div id="move"></div>
      </div>
        <div id="bimg">
              <img id="b_bimg" src="images/1.png" alt="#">
        </div>

css部分

            *{
  margin
:0px; padding:0px; } #box{ width:330px; height:330px; float: left; margin-left:17%; position:relative; } #move{ background-image:url(images/move.png); width:100px; height:100px; position:absolute; left:0px; top:0px; display:none; } #bimg{ width:400px; height:400px; overflow:hidden; float
: left; margin-left: 20px; position: relative; display:none; } #bimg img{ width:1000px; height:1000px; position:absolute; top:0px; left:0px; }

js部分

function bigimg(){
  var bbox = document.getElementById("box");
  var bmove = document.getElementById("move");
  var bbimg = document.getElementById("bimg");
  
var b_bimg = document.getElementById("b_bimg"); bbox.onmouseover = function(){//鼠標移動到box上顯示大圖片和選框 bbimg.style.display = "block"; bmove.style.display="block"; } bbox.onmouseout = function(){//鼠標移開box不顯示大圖片和選框 bbimg.style.display = "none"; bmove.style.display="none"; } bbox.onmousemove = function(e){//獲取鼠標位置 var e=e=e||window.event; var x = e.clientX;//鼠標相對於視口的位置 var y = e.clientY; var t = bbox.offsetTop;//box相對於視口的位置 var l = bbox.offsetLeft; var _left = x - l - bmove.offsetWidth/2;//計算move的位置left值 var _top = y - t -bmove.offsetHeight/2;//計算move的位置top值 if(_top<=0){//滑到box的最頂部 _top = 0; }else if(_top>=bbox.offsetHeight-bmove.offsetHeight){//滑到box的最底部 _top = bbox.offsetHeight-bmove.offsetHeight ;//bbox.offsetHeight-bmove.offsetHeight這是top的最大值 } if(_left<=0){//滑到box的最左邊 _left=0; } else if(_left>=bbox.offsetWidth-bmove.offsetWidth){//滑到box的最右邊 _left=bbox.offsetWidth-bmove.offsetWidth ;//bbox.offsetWidth-bmove.offsetWidth這是left的最大值 } bmove.style.top = _top +"px";//設置move的位置 bmove.style.left = _left + "px"; var w =b_bimg.offsetWidth/bbox.offsetWidth;//計算移動的比例大圖寬除以小圖寬 var h =b_bimg.offsetHeight/bbox.offsetHeight; var b_bimg_top = _top*h;//計算大圖的位置 var b_bimg_left = _left*w; b_bimg.style.top = -b_bimg_top + "px";//設置大圖的位置信息 b_bimg.style.left = -b_bimg_left + "px"; } } bigimg()

效果如下

技術分享圖片

js實現放大鏡效果