隨筆-放大鏡效果
<!doctype html>
<html>
<head>
<meta charset=‘utf-8‘>
<title>隨筆-放大鏡效果</title>
<style>
#box {
margin: 100px;
}
#small {
width: 250px;
height: 250px;
float: left;
border: 1px solid #ccc;
position: relative;
}
#mask {
width: 80px;
height: 80px;
background: rgba(0,0,0,.8);
position: absolute;
left: 0;
top: 0;
display: none;
}
#big {
width: 250px;
height: 250px;
overflow: hidden;
border: 1px solid #ccc;
float: left;
display: none;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload = function(){
//創建一個函數方便獲取各個 ID
function getId(id){
return document.getElementById(id);
}
var box = getId(‘box‘);
var samll = getId(‘small‘);
var mask = getId(‘mask‘);
var big = getId(‘big‘);
var bigPic = big.children[0];
//通過鼠標經過small,焦點框出現,展示圖片也出現,相反鼠標移出都隱藏
small.onmouseover = function(){
mask.style.display = ‘block‘;
big.style.display = ‘block‘;
}
small.onmouseout = function(){
mask.style.display = ‘none‘;
big.style.display = ‘none‘;
}
//鼠標移動 且鼠標在焦點框中心位置
mask.onmousemove = function(e){
var x = box.offsetLeft; //獲取裝圖片的盒子的真實位置
var y = box.offsetTop;
var currentX = e.clientX; //獲取鼠標的位置
var currentY = e.clientY;
var l = currentX - x - mask.offsetWidth/2; //用鼠標位置減去圖片盒子的位置得出small和mask的距離,再減去mask寬高的一半就到中心了
var t = currentY - y -mask.offsetHeight/2;
//限制焦點框只能在samll裏面移動,不能超過small框外
if(x < 0){x = 0}
if(x > small.offsetWidth - mask.offsetWidth){
x = small.offsetWidth - mask.offsetWidth;
}
if(y < 0){y = 0}
if(y > small.offsetHeight - mask.offsetHeight){
y = small.offsetHeight - mask.offsetHeight;
}
//放大鏡展示 用 負的margin 值操作放大鏡圖片的位置
var L = mask.offsetLeft;
var T = mask.offsetTop;
var Px = pic.offsetWidth/small.offsetWidth; //計算兩張圖的一個比例,再根據焦點的移動乘以比例值來確定放大鏡的圖片的位置
var Py = pic.offsetHeight/small.offsetHeight;
pic.style.marginLeft = -L*Px + ‘px‘; //用負的margin值來操作放大鏡的圖片
pic.style.marginTopt = -T*Py + ‘px‘;
}
}
</script>
<div id="box">
<div id="small">
<img src="pic.jpg" width="250" height="250">
<div id="mask"></div>
</small>
<div id="big">
<img src="pic.jpg" width="500" height="500">
</div>
</div>
</body>
</html>
隨筆-放大鏡效果