大家經常逛淘寶、天貓、京東這類網站的時候往往會看到一些圖片展示的效果,例如:把鼠標放在圖片上右側會出現一個放大的預覽區域,這就是所謂放大鏡效果。今天閑著沒事干,就打算復習一下JavaScript基礎,用一下基礎知識制作一個類似于淘寶的放大鏡效果。
先說一下這個效果需要用到的一些基礎知識:
css相對定位:position:absolute;
鼠標移入移出以及移動事件:onmouseover、onmouseout、onmousemove,記住這些事件一般不會單個出現
獲取鼠標點擊坐標:X軸:clientX,Y軸:clientY
當前元素相對于父元素的左位移:offsetLeft
當前元素相對于父元素的上位移:offsetTop
當前元素的實際高、寬度(不包括滾動條):offsetWidth、offsetHeight
球當前元素的最小值,最大值:Math.min()、Math.max();
話不多說直接上代碼吧!
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>放大鏡效果</title><style type="text/css">*{padding: 0;margin: 0;}#demo{display: block;width: 400px;height: 255px;margin: 50px;position: relative;border: 1px solid #ccc;}#float-box{position: relative;z-index: 1;}#small-box{display: none;width: 160px;height: 120px;position: absolute;background: #ffffcc;border: 1px solid #ccc;filter: alpha(opacity=50);opacity: 0.5;cursor: move;}#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></head><body><div id="demo"><div id="float-box"><div id="small-box"></div><img src="../images/macbook-small.jpg"></div><div id="big-box"><img src="../images/macbook-big.jpg"></div></div><script type="text/javascript">window.onload = function(){ //獲取到需要的元素var demo = document.getElementById('demo');var smallBbox = document.getElementById('small-box');var floatBox = document.getElementById('float-box');var bigBox = document.getElementById('big-box');var bigBoxImg = bigBox.getElementsByTagName('img')[0]; floatBox.onmouseover = function(){smallBbox.style.display = "block";bigBox.style.display = "block";}floatBox.onmouseout = function(){smallBbox.style.display = "none";bigBox.style.display = "none";}floatBox.onmousemove = function(e){var _event = e || event;console.log(_event.clientY);var l = _event.clientX - demo.offsetLeft - floatBox.offsetLeft - smallBbox.offsetWidth/2;//除2是因為讓鼠標點出現在放大遮罩的中心位置var t = _event.clientY - demo.offsetTop - floatBox.offsetTop - smallBbox.offsetHeight/2; var demoWidth = demo.offsetWidth;var demoHeight = demo.offsetHeight; var smallBboxWidth = smallBbox.offsetWidth;var smallBboxHeight = smallBbox.offsetHeight;//鼠標可以移動的最大XY的距離var maxX = demoWidth - smallBboxWidth;var maxY = demoHeight - smallBboxHeight; l = Math.min(maxX,Math.max(0,l));t = Math.min(maxY,Math.max(0,t));smallBbox.style.left = l +"px";smallBbox.style.top = t +"px"; var percentX = l / (floatBox.offsetWidth - smallBboxWidth);//求出小圖遮罩的坐標占可移動區域的比例var percentY = t / (floatBox.offsetHeight - smallBboxHeight); bigBoxImg.style.left = -percentX *(bigBoxImg.offsetWidth - bigBox.offsetWidth) +"px";//大圖對的移動方向和小圖遮罩的移動方向相反bigBoxImg.style.top = -percentY*(bigBoxImg.offsetHeight - bigBox.offsetHeight)+"px"; }}</script></body></html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答