javascript放大镜效果的简单实现
这个效果并不难,要点是位置和比例设置,
捕获鼠标位置、判断鼠标位置区域、还有onmouseover事件、onmousemove事件、onmouseout事件
设置显示大图的比例,小图上显示的切图比例都要弄准确点,最好是2倍啦,4倍啦。
主要注意宽度,我这里的图片m.jpg是1440X900的....
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXhtml1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
<title>放大镜效果</title>
<styletype="text/css">
*{margin:0;padding:0;}
#smallimg{width:360px;float:left;position:relative;border:1pxsolidred;}
#smallimgimg{ width:360px;}
#bigimg{float:left;width:400px;height:400px;margin-left:40px;border:1pxsolid#ccc;display:none;}
#showimg{width:100px;height:100px;background:#fff;cursor:move; position:absolute;border:1pxsolid#666;opacity:0.5;filter:alpha(opacity=50);display:none;}
</style>
</head>
<body>
<divid="smallimg">
<imgsrc="jq/m.jpg"alt=""/>
<divid="showimg"> </div>
</div>
<divid="bigimg"> </div>
<scripttype="text/javascript">
var$=function(id){returntypeofid=="string"?document.getElementById(id):id}
varsmallimg=$("smallimg");
varshowimg=$("showimg");//滤镜图片
varbigimg=$("bigimg");
varsmall_url=smallimg.getElementsByTagName("img")[0].getAttribute("src");
varshow_half=maxWidth=maxHeight=0;
smallimg.onmouseover=function(){
showimg.style.display="block";
bigimg.style.display="inline";
show_half=showimg.offsetHeight/2;
maxWidth=smallimg.clientWidth-showimg.offsetWidth;
maxHeight=smallimg.clientHeight-showimg.offsetHeight;
//上面两个变量指明showimg允许活动的区域
};
smallimg.onmousemove=function(e){
vare=window.event?window.event:e;
varnum=bigimg.clientWidth/showimg.clientWidth;
varTop=e.clientY-smallimg.offsetTop-show_half;
varLeft=e.clientX-smallimg.offsetLeft-show_half;
//获取当前移动的showimg位置计算方法是鼠标坐标-最外面容器的坐标-盒子的宽(高)的/2
Top=Top<0?0:Top>maxHeight?maxHeight:Top;
Left=Left<0?0:Left>maxWidth?maxWidth:Left;
showimg.style.top=Top+"px";
showimg.style.left=Left+"px";
bigimg.style.background="url("+small_url+")-"+Left*num+"px-"+Top*num+"pxno-repeat";
};
smallimg.onmouseout=function(){
showimg.style.display="none";
bigimg.style.background="";
bigimg.style.display="none"
};
</script>
</body>
</html>
相关文章
- JavaScript——数组
- 使用JavaScript的数组实现数据结构中的队列与堆栈详解编程语言
- javascript操作文本框readOnly
- 实现javascript的延期执行或者重复执行的两个函数
- javascript动态添加单元格的脚本代码
- 用JavaScript实现UrlEncode和UrlDecode的脚本代码
- 一个简单的JavaScript数据缓存系统实现代码
- javascript倒计时功能实现代码
- JavaScript实现快速排序(自已编写)
- javascript之典型高阶函数应用介绍
- 用原生JavaScript实现jQuery的$.getJSON的解决方法
- 在JavaScript中实现类的方式探讨
- 如何在JavaScript中实现私有属性的写类方式(二)
- js(JavaScript)实现TAB标签切换效果的简单实例
- JavaScript实现存储HTML字符串示例
- javascript实例--教你实现扑克牌洗牌功能
- Javascript实现简单的富文本编辑器附演示
- Javascript基础教程之数据类型(数值Number)
- 深入理解javascript构造函数和原型对象