放大鏡二:大圖的移動
阿新 • • 發佈:2018-03-03
scrip padding lang all span pre mouseover gre eight
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="jquery.js"></script> <style> *{ margin: 0px; padding: 0px; } .outer{ margin-left: 250px; margin-top: 250px; width:311px; height: 207px; position: relative; border:5px dashed lawngreen; } .float{ height:150px; width:150px; background-color: darkgray; opacity: 0.5; position: absolute; } .outer .small_box{ height:207px; } .outer .big_box{ position: absolute; top:-5px; left:321px; border: 5px dashed darkorange; width: 300px; height: 300px; overflow: hidden; } .outer .big_box img{ position: absolute; } .hide{ display: none; } </style> <body> <div class="outer"> <div class="small_box"> <div class="float hide"> </div> <img src="small.jpg"/> </div> <div class="big_box hide"> <img src="big.jpg"/> </div> </div> </body> </html> <script> $(".small_box").mouseover(function(){ $(".float").removeClass(‘hide‘); $(".big_box").removeClass("hide"); }) $(".small_box").mouseout(function(){ $(".float").addClass(‘hide‘); $(".big_box").addClass("hide"); }) $(".small_box").mousemove(function (e) { //防止其獲取坐標出錯 var _event=e || windows.event; //圖片所在文檔的偏移位置 var small_box_offset_top=$(".small_box").offset().top; var small_box_offset_left=$(".small_box").offset().left; //圖片框的大小 var small_box_height=$(".small_box").height(); var small_box_width=$(".small_box").width(); //遮罩層的大小,取一半,為後面遮罩層四邊和鼠標做準備 var float_height=$(".float").height()/2; var float_width=$(".float").width()/2; //面板可移動面積:只有中間區域,邊界距離為面板的一半是無法移動的 //判斷時將鼠標坐標轉換到面板邊界,然後與小照片相比 //鼠標為遮罩層的中心,獲取遮罩層的四邊,以便限制移動 var mouse_left=_event.clientX-float_width; var mouse_top=_event.clientY-float_height; var mouse_right=_event.clientX+float_width; var mouse_bottom=_event.clientY+float_height; //遮罩層應該移動的距離 var move_left=mouse_left-small_box_offset_left; var move_top=mouse_top-small_box_offset_top; if(mouse_top<=small_box_offset_top) move_top=0; if(mouse_bottom>small_box_offset_top+small_box_height) move_top=small_box_height-float_height*2; if(mouse_left<=small_box_offset_left) move_left=0; if(mouse_right>small_box_offset_left+small_box_width) move_left=small_box_width-float_width*2; $(".float").css(‘left‘,move_left+‘px‘); $(".float").css(‘top‘,move_top+‘px‘); //大圖移動 //大小圖比例獲取 2:1 這是大小圖片之比 var x_scan=$(‘.big_box img‘).height()/small_box_height; var y_scan=$(".big_box img").width()/small_box_width; //比例另外獲取方法: 這是大小框可移動長度之比(更適用大多數情況) var x_scan=($(‘.big_box img‘).height()-$(".big_box").height())/(small_box_height-float_height*2); var y_scan=($(".big_box img").width()-$(".big_box").width())/(small_box_width-float_width*2); //大小圖的移動是相對的,成倍數的 $(".big_box img").css(‘top‘,-move_top*x_scan+‘px‘); $(".big_box img").css(‘left‘,-move_left*y_scan+‘px‘); }) </script>
放大鏡二:大圖的移動