HTML CSS寫商品詳情放大鏡效果
阿新 • • 發佈:2019-02-13
先上效果圖:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin: 0px;padding: 0px;}
#small{width: 170px;height: 170px;background:url(img/2.jpg);border: 1px solid#000000;margin :50px;float: left;position: relative;}
#big{width: 170px;height: 170px;background:url(img/1.jpg);border: 1px solid#000000;float:left;margin-top: 50px;display: none;}
#search{width: 72px;height: 72px;background: pink;opacity: 0.5;display: none;position: absolute;position: absolute;}
</style>
</head>
<body>
<!--顯示衣服的DIV-->
<div id="small">
<!--顯示需要檢視的放大區域-->
<div id="search"></div>
</div>
<!--顯示放大區域-->
<div id="big"></div>
</body>
<script type="text/javascript">
var small=document.getElementById("small");
var big=document.getElementById("big");
var search=document.getElementById("search");
//滑鼠移入small時顯示search和big
small.onmouseover=function(){
big.style.display="block";
search.style.display="block";
}
//滑鼠移出small時隱藏search和big
small.onmouseout=function(){
big.style.display="none";
search.style.display="none";
}
small.onmousemove=function(){
var evt=event||arguments[0];
//獲取當前滑鼠座標
var x=evt.clientX-small.offsetLeft-search.offsetWidth/2;
var y=evt.clientY-small.offsetTop-search.offsetHeight/2;
//判斷當前位置search顯示框不能移出small框
if(x<0){
search.style.left=0+"px";
}else if(x>=small.offsetWidth-search.offsetWidth){
search.style.left=small.offsetWidth-search.offsetWidth+"px";
}else{
search.style.left=x+"px";
}
if(y<0){
search.style.top=0+"px";
}else if(y>=small.offsetHeight-search.offsetHeight){
search.style.top=small.offsetHeight-search.offsetHeight+"px";
}else{
search.style.top=y+"px";
}
//計算放大比例,這個比例是大圖片和小圖片的比例
var w=400/170;
//顯示放大區域
big.style.backgroundPosition=(-search.offsetLeft)*w+"px"+" "+(-search.offsetTop)*w+"px";
}
</script>
</html>
原圖: