自己動手豐衣足食之圖片放大鏡
阿新 • • 發佈:2018-12-19
(function() { var oSmall = document.getElementById('small'); var oFloat = document.getElementById('float'); var oBig = document.getElementById('big'); var oImg = oBig.getElementsByTagName('img')[0]; oSmall.onmouseover = function () { oBig.style.display = 'block'; oFloat.style.display = 'block'; } oSmall.onmouseout = function() { oBig.style.display = 'none'; oFloat.style.display = 'none'; } oSmall.onmousemove = function (ev) { var oEvent = ev || event; /*****************/ var zb = document.getElementById('zb'); zb.innerHTML = "滑鼠指標clientX,clientY的座標:" + oEvent.clientX + "," + oEvent.clientY; zb.innerHTML = zb.innerHTML + ",</br>oSmall的offsetLeft,offsetTop:" + oSmall.offsetLeft + "," + oSmall.offsetTop; zb.innerHTML = zb.innerHTML + ",</br>oFloat的offsetWidth,offsetHeight:" + oFloat.offsetWidth + "," + oFloat.offsetHeight; /*****************/ /*計算出滑塊的left,top*/ var l = oEvent.clientX - oSmall.offsetLeft - oFloat.offsetWidth / 2; var t = oEvent.clientY - oSmall.offsetTop - oFloat.offsetHeight / 2; if (l < 0) { l = 0 } else if (l > oSmall.offsetWidth - oFloat.offsetWidth) { l = oSmall.offsetWidth - oFloat.offsetWidth } if (t < 0) { t = 0 } else if (t > oSmall.offsetHeight - oFloat.offsetWidth) { t = oSmall.offsetHeight - oFloat.offsetHeight; } oFloat.style.left = l + 'px'; oFloat.style.top = t + 'px'; zb.innerHTML = zb.innerHTML + "<br/>" + l + "," + t; //計算出相對百分比 var percentX = l / (oSmall.offsetWidth - oFloat.offsetWidth); var percentY = t / (oSmall.offsetHeight - oFloat.offsetHeight); oImg.style.left = -percentX * (oBig.offsetWidth) + 'px'; oImg.style.top = -percentY * (oBig.offsetHeight) + 'px'; } })();