
javaScript<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>9-12放大镜效果</title>
<meta name="Author" content="雪玲珑">
<meta name="Keywords" content="JS 放大镜">
<meta name="Description" content="这是使用JS实现放大镜效果的代码">
<style type="text/css">
*{margin: 0;padding: 0}
body,html{height:100%;cursor: crosshair;}
.pic{width: 200px;height:200px;float: left;position:relative; overflow: hidden;}
.pic img{width:200px;height: 200px;}
.pic #drag{width: 100px;height: 100px;background: yellow;position: absolute;left: 0;top: 0;opacity:0.4;filter:alpha(opacity=40);cursor: move;display: none;}
.bigpic{width: 250px;height:250px;float:left;background: url(image/sky.jpg) center center no-repeat;background-position: 30px 30px;display: none;overflow: hidden;}
#box{width: 500px;height: 500px;}
</style></head>
<body>
<div class="pic" id="pic">
<img id='leftImg'src="http://blog.163.com/image/sky.jpg" alt="原图">
<div id='drag'></div>
</div>
<div class="bigpic" id="bigpic">
<img id='box'src="http://blog.163.com/image/sky.jpg">
</div>
</body>
</html>
<script type="text/javascript">
var pic=document.getElementById('pic');
var bigpic=document.getElementById('bigpic');
var box=document.getElementById('box');
var drag=document.getElementById('drag');
var leftImg=document.getElementById('leftImg');
pic.onmouseout=function(){
//鼠标移出 滤镜和右边图隐藏
drag.style.display='none';
bigpic.style.display='none';
}
pic.onmousemove=function(event){
var e=event||window.event;
drag.style.display='block' //当鼠标移上并移动的时候,滤镜层是可以显示的
bigpic.style.display='block' //当鼠标移上并移动的时候,右边大图层也是可以显示的
//获取鼠标的位置,即鼠标距离窗口的值
var x=e.clientX;
var y=e.clientY;
//x-pic.offsetleft的值是鼠标相对于外边图左边距的距离。(offsetleft是对象与窗口左边的距离,=父border+父padding+左margin)
//因为想要鼠标位置位于滤镜的中心,所以在计算滤镜距外边图左边界的距离时还要减去滤镜宽度的一半
//offsetWidth:对象的宽度,即offsetWidth=width+padding+border=clientWidth+border
var lefts=x-pic.offsetLeft-drag.offsetWidth/2;
var tops=y-pic.offsetTop-drag.offsetHeight/2;
//临界值判断 left需要在0和(pic.clientWidth-drag.offsetWidth)之间
if (lefts<0){lefts=0;}
if (lefts>pic.clientWidth-drag.offsetWidth) {lefts=pic.clientWidth-drag.offsetWidth};
if (tops<0){tops=0;}
if (tops>pic.clientHeight-drag.offsetHeight) {tops=pic.clientHeight-drag.offsetHeight};
//现在可以确定滤镜相对于外边图的位置,注意drag.style.left需要有‘px’的单位。
drag.style.left=lefts+'px';
drag.style.top=tops+'px';
//现在控制右边大图的位置,即得到右边显示区域的scrollLeft和scrollTop.,
//根据比例关系 倍数=左边图的宽高/原大图宽高=滤镜宽高/右边显示区域宽高=滤镜距左边界距离/右大图距原图左边界距离.
var num=box.offsetWidth/leftImg.offsetWidth;
bigpic.scrollLeft=drag.offsetLeft*num;
bigpic.scrollTop=drag.offsetTop*num;
}
</script>
本文介绍了一种使用JavaScript实现的网页商品图片放大镜效果的方法。通过鼠标悬停和移动操作,用户可以在一个小区域内查看放大的商品细节。此效果有助于提高电子商务网站的用户体验。

497

被折叠的 条评论
为什么被折叠?



