客户有个需求,就是要在产品展示的时候,需要会图片放大预览的效果,OK,很简单~大家完全可以把下面的Copy过去,用到项目中去!
最主要的是下面这个JS文件,我加了点注释:
JS:
(function($){
$.fn.jqueryzoom = function(options){
//设置预览的边框属性
var settings = {
xzoom: 200, //宽
yzoom: 200, //高
offset: 10, //与原图的距离
position: "right" //预览显示的停靠位置,可以改为左边(left)等其他地方
};
//这里相当与初始化设置给传入的对象
if(options) {
$.extend(settings, options);
}
//鼠标悬停的效果
$(this).hover(function(){
//设置大小
var imageLeft = $(this).get(0).offsetLeft;
var imageRight = $(this).get(0).offsetRight;
var imageTop = $(this).get(0).offsetTop;
var imageWidth = $(this).get(0).offsetWidth;
var imageHeight = $(this).get(0).offsetHeight;
//添加alt属性
var bigimage = $(this).attr("alt");
//判断div.zoomdiv是否存在,如果不存在,就在传入对象的后面插入
if($("div.zoomdiv").get().length == 0){
$(this).after("<div class='zoomdiv'><img class='bigimg' src='"+bigimage+"'/></div>");
}
//判断停靠位置
if(settings.position == "right"){
leftpos = imageLeft + imageWidth + settings.offset; //自己想下问什么,很清楚了
}else{
leftpos = imageLeft - settings.xzoom - settings.offset;
}
//添加样式表和设置高 宽
$("div.zoomdiv").css({ top: imageTop,left: leftpos });
$("div.zoomdiv").width(settings.xzoom);
$("div.zoomdiv").height(settings.yzoom);
$("div.zoomdiv").show();
//鼠标移除效果
$(document.body).mousemove(function(e){
//预览图片的class的宽和高
var bigwidth = $(".bigimg").get(0).offsetWidth;
var bigheight = $(".bigimg").get(0).offsetHeight;
var scaley ='x';
var scalex= 'y';
if(isNaN(scalex)|isNaN(scaley)){
var scalex = Math.round(bigwidth/imageWidth) ;
var scaley = Math.round(bigheight/imageHeight);
}
mouse = new MouseEvent(e); //这里调用函数
scrolly = mouse.y - imageTop - ($("div.zoomdiv").height()*1/scaley)/2 ;
$("div.zoomdiv").get(0).scrollTop = scrolly * scaley ;
scrollx = mouse.x - imageLeft - ($("div.zoomdiv").width()*1/scalex)/2 ;
$("div.zoomdiv").get(0).scrollLeft = (scrollx) * scalex ;
});
},function(){
$("div.zoomdiv").hide();
$(document.body).unbind("mousemove");
$(".lenszoom").remove();
$("div.zoomdiv").remove();
});
}
})(jQuery); //单例
//设置传入对象的x,y是鼠标相应与左上角的位置
function MouseEvent(e) {
this.x = e.pageX
this.y = e.pageY
}
由于这个文件,是基于jquery的,所以,我们在使用的时候要用到Jquery(我很喜欢),具体看下面:
<html>
<head>
<meta http-equiv="Content-Type" c>
<title>产品图片展示</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.jqzoom.js"></script>
<script type="text/javascript">
//使用方法,就是这么简单
jQuery.noConflict();
jQuery(document).ready(function(){
$("img.jqzoom").jqueryzoom();
});
</script>
<style type="text/css">
/*
一些基本样式,大家可以自己修改
*/
img{
border:0px;
}
div.zoomdiv {
z-index : 100;
position : absolute;
top:0px;
left:0px;
width : 200px;
height : 200px;
background: #ffffff;
border:1px solid #CCCCCC;
display:none;
text-align: center;
overflow: hidden;
}
img.jqzoom{
cursor:crosshair;
position:relative;
}
</style>
</head>
<body>
<img src="images/shoe1_small.jpg" class="jqzoom" alt="images/shoe1_big.jpg">
</body>
</html>
简单说明下:一般地是需要来2张图片的,一大一小!
原文出处:
http://www.cnblogs.com/zh-cn