jquery图片放大镜功能的实例代码

实现原理:

图片 1

图片 2

淘宝上经常用到的一个功能是利用图片的放大镜功能来查看商品的细节

jQuery实现图片局部放大镜效果,jquery放大镜

下图只是给大家举个例子,类似于这种效果图:

图片 3

具体实现过程请看下文代码:

css

.zoomPad{
position:relative;
float:left;
z-index:99;
cursor:crosshair;
}
.zoomPreload{
-moz-opacity:0.8;
opacity: 0.8;
filter: alpha(opacity = 80);
color: #333;
font-size: 12px;
font-family: Tahoma;
text-decoration: none;
border: 1px solid #CCC;
padding: 8px;
text-align:center;
background-image: url(../images/zoomloader.gif);
background-repeat: no-repeat;
background-position: 43px 30px;
z-index:110;
width:90px;
height:43px;
position:absolute;
top:0px;
left:0px;
* width:100px;
* height:49px;
}
.zoomPup{
overflow:hidden;
-moz-opacity:0.6;
opacity: 0.6;
filter: alpha(opacity = 60);
z-index:120;
position:absolute;
border:1px solid #CCC;
z-index:101;
cursor:crosshair;
}
.zoomOverlay{
position:absolute;
left:0px;
top:0px;
/*opacity:0.5;*/
z-index:5000;
width:100%;
height:100%;
display:none;
z-index:101;
}
.zoomWindow{
position:absolute;
left:110%;
top:40px;
z-index:6000;
height:auto;
z-index:10000;
z-index:110;
}
.zoomWrapper{
position:relative;
border:1px solid #999;
z-index:110;
}
.zoomWrapperTitle{
display:block;
background:#999;
color:#FFF;
height:18px;
line-height:18px;
width:100%;
overflow:hidden;
text-align:center;
font-size:10px;
position:absolute;
top:0px;
left:0px;
z-index:120;
-moz-opacity:0.6;
opacity: 0.6;
filter: alpha(opacity = 60);
}
.zoomWrapperImage{
display:block;
position:relative;
overflow:hidden;
z-index:110;
}
.zoomWrapperImage img{
border:0px;
display:block;
position:absolute;
z-index:101;
}
.zoomIframe{
z-index: -1;
filter:alpha(opacity=0);
-moz-opacity: 0.80;
opacity: 0.80;
position:absolute;
display:block;
}
/*********************************************************
/ When clicking on thumbs jqzoom will add the class
/ "zoomThumbActive" on the anchor selected
/*********************************************************/ 

js

/*!
* jQzoom Evolution Library v2.3 - Javascript Image magnifier
* http://www.mind-projects.it
*
* Copyright 2011, Engineer Marco Renzi
* Licensed under the BSD license.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the organization nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Date: 03 May 2011 22:16:00
*/
(function ($) {
//GLOBAL VARIABLES
var isIE6 = ($.browser.msie && $.browser.version < 7);
var body = $(document.body);
var window = $(window);
var jqzoompluging_disabled = false; //disabilita globalmente il plugin
$.fn.jqzoom = function (options) {
return this.each(function () {
var node = this.nodeName.toLowerCase();
if (node == 'a') {
new jqzoom(this, options);
}
});
};
jqzoom = function (el, options) {
var api = null;
api = $(el).data("jqzoom");
if (api) return api;
var obj = this;
var settings = $.extend({}, $.jqzoom.defaults, options || {});
obj.el = el;
el.rel = $(el).attr('rel');
//ANCHOR ELEMENT
el.zoom_active = false;
el.zoom_disabled = false; //to disable single zoom instance
el.largeimageloading = false; //tell us if large image is loading
el.largeimageloaded = false; //tell us if large image is loaded
el.scale = {};
el.timer = null;
el.mousepos = {};
el.mouseDown = false;
$(el).css({
'outline-style': 'none',
'text-decoration': 'none'
});
//BASE IMAGE
var img = $("img:eq(0)", el);
el.title = $(el).attr('title');
el.imagetitle = img.attr('title');
var zoomtitle = ($.trim(el.title).length > 0) ? el.title : el.imagetitle;
var smallimage = new Smallimage(img);
var lens = new Lens();
var stage = new Stage();
var largeimage = new Largeimage();
var loader = new Loader();
//preventing default click,allowing the onclick event [exmple: lightbox]
$(el).bind('click', function (e) {
e.preventDefault();
return false;
});
//setting the default zoomType if not in settings
var zoomtypes = ['standard', 'drag', 'innerzoom', 'reverse'];
if ($.inArray($.trim(settings.zoomType), zoomtypes) < 0) {
settings.zoomType = 'standard';
}
$.extend(obj, {
create: function () { //create the main objects
//create ZoomPad
if ($(".zoomPad", el).length == 0) {
el.zoomPad = $('<div/>').addClass('zoomPad');
img.wrap(el.zoomPad);
}
if(settings.zoomType == 'innerzoom'){
settings.zoomWidth = smallimage.w;
settings.zoomHeight = smallimage.h;
}
//creating ZoomPup
if ($(".zoomPup", el).length == 0) {
lens.append();
}
//creating zoomWindow
if ($(".zoomWindow", el).length == 0) {
stage.append();
}
//creating Preload
if ($(".zoomPreload", el).length == 0) {
loader.append();
}
//preloading images
if (settings.preloadImages || settings.zoomType == 'drag' || settings.alwaysOn) {
obj.load();
}
obj.init();
},
init: function () {
//drag option
if (settings.zoomType == 'drag') {
$(".zoomPad", el).mousedown(function () {
el.mouseDown = true;
});
$(".zoomPad", el).mouseup(function () {
el.mouseDown = false;
});
document.body.ondragstart = function () {
return false;
};
$(".zoomPad", el).css({
cursor: 'default'
});
$(".zoomPup", el).css({
cursor: 'move'
});
}
if (settings.zoomType == 'innerzoom') {
$(".zoomWrapper", el).css({
cursor: 'crosshair'
});
}
$(".zoomPad", el).bind('mouseenter mouseover', function (event) {
img.attr('title', '');
$(el).attr('title', '');
el.zoom_active = true;
//if loaded then activate else load large image
smallimage.fetchdata();
if (el.largeimageloaded) {
obj.activate(event);
} else {
obj.load();
}
});
$(".zoomPad", el).bind('mouseleave', function (event) {
obj.deactivate();
});
$(".zoomPad", el).bind('mousemove', function (e) {
//prevent fast mouse mevements not to fire the mouseout event
if (e.pageX > smallimage.pos.r || e.pageX < smallimage.pos.l || e.pageY < smallimage.pos.t || e.pageY > smallimage.pos.b) {
lens.setcenter();
return false;
}
el.zoom_active = true;
if (el.largeimageloaded && !$('.zoomWindow', el).is(':visible')) {
obj.activate(e);
}
if (el.largeimageloaded && (settings.zoomType != 'drag' || (settings.zoomType == 'drag' && el.mouseDown))) {
lens.setposition(e);
}
});
var thumb_preload = new Array();
var i = 0;
//binding click event on thumbnails
var thumblist = new Array();
thumblist = $('a').filter(function () {
var regex = new RegExp("gallery[\\s]*:[\\s]*'" + $.trim(el.rel) + "'", "i");
var rel = $(this).attr('rel');
if (regex.test(rel)) {
return this;
}
});
if (thumblist.length > 0) {
//getting the first to the last
var first = thumblist.splice(0, 1);
thumblist.push(first);
}
thumblist.each(function () {
//preloading thumbs
if (settings.preloadImages) {
var thumb_options = $.extend({}, eval("(" + $.trim($(this).attr('rel')) + ")"));
thumb_preload[i] = new Image();
thumb_preload[i].src = thumb_options.largeimage;
i++;
}
$(this).click(function (e) {
if($(this).hasClass('zoomThumbActive')){
return false;
}
thumblist.each(function () {
$(this).removeClass('zoomThumbActive');
});
e.preventDefault();
obj.swapimage(this);
return false;
});
});
},
load: function () {
if (el.largeimageloaded == false && el.largeimageloading == false) {
var url = $(el).attr('href');
el.largeimageloading = true;
largeimage.loadimage(url);
}
},
activate: function (e) {
clearTimeout(el.timer);
//show lens and zoomWindow
lens.show();
stage.show();
},
deactivate: function (e) {
switch (settings.zoomType) {
case 'drag':
//nothing or lens.setcenter();
break;
default:
img.attr('title', el.imagetitle);
$(el).attr('title', el.title);
if (settings.alwaysOn) {
lens.setcenter();
} else {
stage.hide();
lens.hide();
}
break;
}
el.zoom_active = false;
},
swapimage: function (link) {
el.largeimageloading = false;
el.largeimageloaded = false;
var options = new Object();
options = $.extend({}, eval("(" + $.trim($(link).attr('rel')) + ")"));
if (options.smallimage && options.largeimage) {
var smallimage = options.smallimage;
var largeimage = options.largeimage;
$(link).addClass('zoomThumbActive');
$(el).attr('href', largeimage);
img.attr('src', smallimage);
lens.hide();
stage.hide();
obj.load();
} else {
alert('ERROR :: Missing parameter for largeimage or smallimage.');
throw 'ERROR :: Missing parameter for largeimage or smallimage.';
}
return false;
}
});
//sometimes image is already loaded and onload will not fire
if (img[0].complete) {
//fetching data from sallimage if was previously loaded
smallimage.fetchdata();
if ($(".zoomPad", el).length == 0) obj.create();
}
/*========================================================,
| Smallimage
|---------------------------------------------------------:
| Base image into the anchor element
`========================================================*/
function Smallimage(image) {
var $obj = this;
this.node = image[0];
this.findborder = function () {
var bordertop = 0;
bordertop = image.css('border-top-width');
btop = '';
var borderleft = 0;
borderleft = image.css('border-left-width');
bleft = '';
if (bordertop) {
for (i = 0; i < 3; i++) {
var x = [];
x = bordertop.substr(i, 1);
if (isNaN(x) == false) {
btop = btop + '' + bordertop.substr(i, 1);
} else {
break;
}
}
}
if (borderleft) {
for (i = 0; i < 3; i++) {
if (!isNaN(borderleft.substr(i, 1))) {
bleft = bleft + borderleft.substr(i, 1)
} else {
break;
}
}
}
$obj.btop = (btop.length > 0) ? eval(btop) : 0;
$obj.bleft = (bleft.length > 0) ? eval(bleft) : 0;
};
this.fetchdata = function () {
$obj.findborder();
$obj.w = image.width();
$obj.h = image.height();
$obj.ow = image.outerWidth();
$obj.oh = image.outerHeight();
$obj.pos = image.offset();
$obj.pos.l = image.offset().left + $obj.bleft;
$obj.pos.t = image.offset().top + $obj.btop;
$obj.pos.r = $obj.w + $obj.pos.l;
$obj.pos.b = $obj.h + $obj.pos.t;
$obj.rightlimit = image.offset().left + $obj.ow;
$obj.bottomlimit = image.offset().top + $obj.oh;
};
this.node.onerror = function () {
alert('Problems while loading image.');
throw 'Problems while loading image.';
};
this.node.onload = function () {
$obj.fetchdata();
if ($(".zoomPad", el).length == 0) obj.create();
};
return $obj;
};
/*========================================================,
| Loader
|---------------------------------------------------------:
| Show that the large image is loading
`========================================================*/
function Loader() {
var $obj = this;
this.append = function () {
this.node = $('<div/>').addClass('zoomPreload').css('visibility', 'hidden').html(settings.preloadText);
$('.zoomPad', el).append(this.node);
};
this.show = function () {
this.node.top = (smallimage.oh - this.node.height()) / 2;
this.node.left = (smallimage.ow - this.node.width()) / 2;
//setting position
this.node.css({
top: this.node.top,
left: this.node.left,
position: 'absolute',
visibility: 'visible'
});
};
this.hide = function () {
this.node.css('visibility', 'hidden');
};
return this;
}
/*========================================================,
| Lens
|---------------------------------------------------------:
| Lens over the image
`========================================================*/
function Lens() {
var $obj = this;
this.node = $('<div/>').addClass('zoomPup');
//this.nodeimgwrapper = $("<div/>").addClass('zoomPupImgWrapper');
this.append = function () {
$('.zoomPad', el).append($(this.node).hide());
if (settings.zoomType == 'reverse') {
this.image = new Image();
this.image.src = smallimage.node.src; // fires off async
$(this.node).empty().append(this.image);
}
};
this.setdimensions = function () {
this.node.w = (parseInt((settings.zoomWidth) / el.scale.x) > smallimage.w ) ? smallimage.w : (parseInt(settings.zoomWidth / el.scale.x)); 
this.node.h = (parseInt((settings.zoomHeight) / el.scale.y) > smallimage.h ) ? smallimage.h : (parseInt(settings.zoomHeight / el.scale.y)); 
this.node.top = (smallimage.oh - this.node.h - 2) / 2;
this.node.left = (smallimage.ow - this.node.w - 2) / 2;
//centering lens
this.node.css({
top: 0,
left: 0,
width: this.node.w + 'px',
height: this.node.h + 'px',
position: 'absolute',
display: 'none',
borderWidth: 1 + 'px'
});
if (settings.zoomType == 'reverse') {
this.image.src = smallimage.node.src;
$(this.node).css({
'opacity': 1
});
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
};
this.setcenter = function () {
//calculating center position
this.node.top = (smallimage.oh - this.node.h - 2) / 2;
this.node.left = (smallimage.ow - this.node.w - 2) / 2;
//centering lens
this.node.css({
top: this.node.top,
left: this.node.left
});
if (settings.zoomType == 'reverse') {
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
//centering large image
largeimage.setposition();
};
this.setposition = function (e) {
el.mousepos.x = e.pageX;
el.mousepos.y = e.pageY;
var lensleft = 0;
var lenstop = 0;
function overleft(lens) {
return el.mousepos.x - (lens.w) / 2 < smallimage.pos.l; 
}
function overright(lens) {
return el.mousepos.x + (lens.w) / 2 > smallimage.pos.r; 
}
function overtop(lens) {
return el.mousepos.y - (lens.h) / 2 < smallimage.pos.t; 
}
function overbottom(lens) {
return el.mousepos.y + (lens.h) / 2 > smallimage.pos.b; 
}
lensleft = el.mousepos.x + smallimage.bleft - smallimage.pos.l - (this.node.w + 2) / 2;
lenstop = el.mousepos.y + smallimage.btop - smallimage.pos.t - (this.node.h + 2) / 2;
if (overleft(this.node)) {
lensleft = smallimage.bleft - 1;
} else if (overright(this.node)) {
lensleft = smallimage.w + smallimage.bleft - this.node.w - 1;
}
if (overtop(this.node)) {
lenstop = smallimage.btop - 1;
} else if (overbottom(this.node)) {
lenstop = smallimage.h + smallimage.btop - this.node.h - 1;
}
this.node.left = lensleft;
this.node.top = lenstop;
this.node.css({
'left': lensleft + 'px',
'top': lenstop + 'px'
});
if (settings.zoomType == 'reverse') {
if ($.browser.msie && $.browser.version > 7) {
$(this.node).empty().append(this.image);
}
$(this.image).css({
position: 'absolute',
display: 'block',
left: -(this.node.left + 1 - smallimage.bleft) + 'px',
top: -(this.node.top + 1 - smallimage.btop) + 'px'
});
}
largeimage.setposition();
};
this.hide = function () {
img.css({
'opacity': 1
});
this.node.hide();
};
this.show = function () { 
if (settings.zoomType != 'innerzoom' && (settings.lens || settings.zoomType == 'drag')) {
this.node.show();
} 
if (settings.zoomType == 'reverse') {
img.css({
'opacity': settings.imageOpacity
});
}
};
this.getoffset = function () {
var o = {};
o.left = $obj.node.left;
o.top = $obj.node.top;
return o;
};
return this;
};
/*========================================================,
| Stage
|---------------------------------------------------------:
| Window area that contains the large image
`========================================================*/
function Stage() {
var $obj = this;
this.node = $("<div class='zoomWindow'><div class='zoomWrapper'><div class='zoomWrapperTitle'></div><div class='zoomWrapperImage'></div></div></div>");
this.ieframe = $('<iframe class="zoomIframe" src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" frameborder="0" ></iframe>');
this.setposition = function () {
this.node.leftpos = 0;
this.node.toppos = 0;
if (settings.zoomType != 'innerzoom') {
//positioning
switch (settings.position) {
case "left":
this.node.leftpos = (smallimage.pos.l - smallimage.bleft - Math.abs(settings.xOffset) - settings.zoomWidth > 0) ? (0 - settings.zoomWidth - Math.abs(settings.xOffset)) : (smallimage.ow + Math.abs(settings.xOffset));
this.node.toppos = Math.abs(settings.yOffset);
break;
case "top":
this.node.leftpos = Math.abs(settings.xOffset);
this.node.toppos = (smallimage.pos.t - smallimage.btop - Math.abs(settings.yOffset) - settings.zoomHeight > 0) ? (0 - settings.zoomHeight - Math.abs(settings.yOffset)) : (smallimage.oh + Math.abs(settings.yOffset));
break;
case "bottom":
this.node.leftpos = Math.abs(settings.xOffset);
this.node.toppos = (smallimage.pos.t - smallimage.btop + smallimage.oh + Math.abs(settings.yOffset) + settings.zoomHeight < screen.height) ? (smallimage.oh + Math.abs(settings.yOffset)) : (0 - settings.zoomHeight - Math.abs(settings.yOffset));
break;
default:
this.node.leftpos = (smallimage.rightlimit + Math.abs(settings.xOffset) + settings.zoomWidth < screen.width) ? (smallimage.ow + Math.abs(settings.xOffset)) : (0 - settings.zoomWidth - Math.abs(settings.xOffset));
this.node.toppos = Math.abs(settings.yOffset);
break;
}
}
this.node.css({
'left': this.node.leftpos + 'px',
'top': this.node.toppos + 'px'
});
return this;
};
this.append = function () {
$('.zoomPad', el).append(this.node);
this.node.css({
position: 'absolute',
display: 'none',
zIndex: 5001
});
if (settings.zoomType == 'innerzoom') {
this.node.css({
cursor: 'default'
});
var thickness = (smallimage.bleft == 0) ? 1 : smallimage.bleft;
$('.zoomWrapper', this.node).css({
borderWidth: thickness + 'px'
}); 
}
$('.zoomWrapper', this.node).css({
width: Math.round(settings.zoomWidth) + 'px' ,
borderWidth: thickness + 'px'
});
$('.zoomWrapperImage', this.node).css({
width: '100%',
height: Math.round(settings.zoomHeight) + 'px'
});
//zoom title
$('.zoomWrapperTitle', this.node).css({
width: '100%',
position: 'absolute'
}); 
$('.zoomWrapperTitle', this.node).hide();
if (settings.title && zoomtitle.length > 0) {
$('.zoomWrapperTitle', this.node).html(zoomtitle).show();
}
$obj.setposition();
};
this.hide = function () {
switch (settings.hideEffect) {
case 'fadeout':
this.node.fadeOut(settings.fadeoutSpeed, function () {});
break;
default:
this.node.hide();
break;
}
this.ieframe.hide();
};
this.show = function () {
switch (settings.showEffect) {
case 'fadein':
this.node.fadeIn();
this.node.fadeIn(settings.fadeinSpeed, function () {});
break;
default:
this.node.show();
break;
}
if (isIE6 && settings.zoomType != 'innerzoom') {
this.ieframe.width = this.node.width();
this.ieframe.height = this.node.height();
this.ieframe.left = this.node.leftpos;
this.ieframe.top = this.node.toppos;
this.ieframe.css({
display: 'block',
position: "absolute",
left: this.ieframe.left,
top: this.ieframe.top,
zIndex: 99,
width: this.ieframe.width + 'px',
height: this.ieframe.height + 'px'
});
$('.zoomPad', el).append(this.ieframe);
this.ieframe.show();
};
};
};
/*========================================================,
| LargeImage
|---------------------------------------------------------:
| The large detailed image
`========================================================*/
function Largeimage() {
var $obj = this;
this.node = new Image();
this.loadimage = function (url) {
//showing preload
loader.show();
this.url = url;
this.node.style.position = 'absolute';
this.node.style.border = '0px';
this.node.style.display = 'none';
this.node.style.left = '-5000px';
this.node.style.top = '0px';
document.body.appendChild(this.node);
this.node.src = url; // fires off async
};
this.fetchdata = function () {
var image = $(this.node);
var scale = {};
this.node.style.display = 'block';
$obj.w = image.width();
$obj.h = image.height();
$obj.pos = image.offset();
$obj.pos.l = image.offset().left;
$obj.pos.t = image.offset().top;
$obj.pos.r = $obj.w + $obj.pos.l;
$obj.pos.b = $obj.h + $obj.pos.t;
scale.x = ($obj.w / smallimage.w);
scale.y = ($obj.h / smallimage.h);
el.scale = scale;
document.body.removeChild(this.node);
$('.zoomWrapperImage', el).empty().append(this.node);
//setting lens dimensions;
lens.setdimensions();
};
this.node.onerror = function () {
alert('Problems while loading the big image.');
throw 'Problems while loading the big image.';
};
this.node.onload = function () {
//fetching data
$obj.fetchdata();
loader.hide();
el.largeimageloading = false;
el.largeimageloaded = true;
if (settings.zoomType == 'drag' || settings.alwaysOn) {
lens.show();
stage.show();
lens.setcenter();
}
};
this.setposition = function () {
var left = -el.scale.x * (lens.getoffset().left - smallimage.bleft + 1);
var top = -el.scale.y * (lens.getoffset().top - smallimage.btop + 1);
$(this.node).css({
'left': left + 'px',
'top': top + 'px'
});
};
return this;
};
$(el).data("jqzoom", obj);
};
//es. $.jqzoom.disable('#jqzoom1');
$.jqzoom = {
defaults: {
zoomType: 'standard',
//innerzoom/standard/reverse/drag
zoomWidth: 300,
//zoomWindow default width
zoomHeight: 300,
//zoomWindow default height
xOffset: 10,
//zoomWindow x offset, can be negative(more on the left) or positive(more on the right)
yOffset: 0,
//zoomWindow y offset, can be negative(more on the left) or positive(more on the right)
position: "right",
//zoomWindow default position
preloadImages: true,
//image preload
preloadText: 'Loading zoom',
title: true,
lens: true,
imageOpacity: 0.4,
alwaysOn: false,
showEffect: 'show',
//show/fadein
hideEffect: 'hide',
//hide/fadeout
fadeinSpeed: 'slow',
//fast/slow/number
fadeoutSpeed: '2000' //fast/slow/number
},
disable: function (el) {
var api = $(el).data('jqzoom');
api.disable();
return false;
},
enable: function (el) {
var api = $(el).data('jqzoom');
api.enable();
return false;
},
disableAll: function (el) {
jqzoompluging_disabled = true;
},
enableAll: function (el) {
jqzoompluging_disabled = false;
}
};
})(jQuery); 

还需要有Jquery.js

使用方法:

1.当页面导入的时候,载入 jQZoom 插件。

$(function(){
$(".jqzoom").jqzoom({
zoomWidth: 300, 
zoomHeight: 300,
lens:true,
preloadImages: false,
alwaysOn:false,
title:false,
xOffset:20,
position: "right"
});
})

2.创建一个放图片的容器,指定一个a标记用于显示放大后的图片的一部分:

<a href="images/BIGIMAGE.JPG" class="jqzoom" title="MYTITLE"> 
<img src="images/SMALLIMAGE.JPG" title="IMAGE TITLE"> 
</a> 

下面给一些基本的配置参数:

•zoomType,默认值:’standard’,另一个值是’reverse’,是否将原图用半透明图层遮盖。

•zoomWidth,默认值:200,放大窗口的宽度。

•zoomHeight,默认值:200,放大窗口的高度。

•xOffset,默认值:10,放大窗口相对于原图的x轴偏移值,可以为负。

•yOffset,默认值:0,放大窗口相对于原图的y轴偏移值,可以为负。

•position,默认值:’right’,放大窗口的位置,值还可以是:’right’ ,’left’
,’top’ ,’bottom’。

•lens,默认值:true,若为false,则不在原图上显示镜头。

•imageOpacity,默认值:0.2,当zoomType的值为’reverse’时,这个参数用于指定遮罩的透明度。

•title,默认值:true,在放大窗口中显示标题,值可以为a标记的title值,若无,则为原图的title值。

•showEffect,默认值:’show’,显示放大窗口时的效果,值可以为: ‘show’
,’fadein’。

•hideEffect,默认值:’hide’,隐藏放大窗口时的效果: ‘hide’ ,’fadeout’。

•fadeinSpeed,默认值:’fast’,放大窗口的渐显速度(选项:
‘fast’,’slow’,’medium’)。

•fadeoutSpeed,默认值:’slow’,放大窗口的渐隐速度(选项:
‘fast’,’slow’,’medium’)。

•showPreload,默认值:true,是否显示加载提示Loading zoom(选项:
‘true’,’false’)。

•preloadText,默认值:’Loading zoom’,自定义加载提示文本。

•preloadPosition,默认值:’center’,加载提示的位置,值也可以为’bycss’,以通过css指定位置。

样式的个性化当然也可以直接修改jqzoom.css文件。

  这里用到了两张图片,一张小图,一张大图。将大图设置为放大镜的背景图片,当鼠标在小图上移动时,同时控制背景大图在放大镜中的位置。两张图片大小最好是等比例的,这样才能达到最佳效果。当没有大图时,则默认为小图本身,这时由于两张图片大小一样,因此放大镜效果不明显,就跟没放大是一样的。

复制代码 代码如下:

复制代码 代码如下:

下面我们来实现这样一个功能吧,原理很简单:

实现一个可以随鼠标移动的虚框

在另外一个块中对应显示虚框中的内容

您可能感兴趣的文章:

  • 关于Jqzoom的使用心得 jquery放大镜效果插件
  • 基于jquery的商品展示放大镜
  • 在jQuery1.5中使用deferred对象 着放大镜看Promise
  • 用JQuery模仿淘宝的图片放大镜显示效果
  • 基于Jquery插件开发之图片放大镜效果(仿淘宝)
  • 基于jquery的放大镜效果
  • jquery插件珍藏(图片局部放大/信息提示框)
  • jquery图片放大镜功能的实例代码

下图只是给大家举个例子,类似于这种效果图: 具体实现过程请看下文代码:
css .zoomPad{posit…

  此插件用到了html5,css3的一些属性,ie8及以下版本不兼容,放大镜是方形的。

/*放大镜*/
.ZoomMain
{margin:100px;width:395px;height:460px;float:left;position:relative;}
.ZoomMain .zoom {height:393px;width:393px;position:relative;border: 1px
solid #dcdddd;}
.ZoomMain .zoom .move{position:absolute;left:0;
top:0;display:none;width:195px;
height:195px;background:#000;opacity:0.2;filter:Alpha(Opacity=20);}
.ZoomMain .zoomDetail{display:none;border:1px solid
#DCDDDD;width:393px; height:393px;
position:absolute;right:-405px;top:0px; overflow:hidden;}
.littleImg
{margin-top:10px;height:54px;overflow:hidden;position:relative;}
.littleImg span {position:
absolute;display:block;width:10px;height:55px;background:#999;cursor:pointer;}
.littleImg span em {display: none;width:10px;height:55px;}
.littleImg span.btnL {left:0;background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat left top;}
.littleImg span.btnL em {background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat left
-57px;}
.littleImg span.btnR em {background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat -10px
-57px;}
.littleImg span.btnR {right:0;background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat -10px
top;}
.littleImg span.hover em {display:block;}
.littleImg .slideMain
{width:343px;height:55px;margin-left:26px;overflow:hidden;position:relative;}
.littleImg .slideMain ul
{position:absolute;left:0;width:355px;padding-top:1px;}
.littleImg .slideMain ul li
{float:left;margin-right:6px;cursor:pointer;width:50px;height:50px;border:1px
solid #dbdbdb;}
.littleImg .slideMain ul li.selected {border-color:#999;}
.littleImg .slideMain ul li img {float:left;width:50px;height:50px;}
/*放大镜end*/
</style>
</head>
<body>
<!–放大镜–>
<div class=”ZoomMain”>
  <div class=”zoom”>
         <span class=”move”></span>
         <img width=”393″ height=”390″  src=”1347000569971.jpg”
/>
  </div>
  <div class=”littleImg”>
       <span class=”btnL”><em></em></span>
       <span class=”btnR”><em></em></span>
        <div class=”slideMain”>
              <ul class=”clearfix”>
                <li class=”selected”><img width=”50″
height=”50″ src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
              </ul>
        </div>
  </div>
  <div class=”zoomDetail”>
            <img width=”701″ height=”701″ src=”1347000569971.jpg”
/>
  </div>
</div>
<!–放大镜end–>
  

/*放大镜*/
.ZoomMain
{margin:100px;width:395px;height:460px;float:left;position:relative;}
.ZoomMain .zoom {height:393px;width:393px;position:relative;border: 1px
solid #dcdddd;}
.ZoomMain .zoom .move{position:absolute;left:0;
top:0;display:none;width:195px;
height:195px;background:#000;opacity:0.2;filter:Alpha(Opacity=20);}
.ZoomMain .zoomDetail{display:none;border:1px solid
#DCDDDD;width:393px; height:393px;
position:absolute;right:-405px;top:0px; overflow:hidden;}
.littleImg
{margin-top:10px;height:54px;overflow:hidden;position:relative;}
.littleImg span {position:
absolute;display:block;width:10px;height:55px;background:#999;cursor:pointer;}
.littleImg span em {display: none;width:10px;height:55px;}
.littleImg span.btnL {left:0;background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat left top;}
.littleImg span.btnL em {background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat left
-57px;}
.littleImg span.btnR em {background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat -10px
-57px;}
.littleImg span.btnR {right:0;background:
url(oohdear/images/cssPos/UltimatePageCssPos.gif) no-repeat -10px
top;}
.littleImg span.hover em {display:block;}
.littleImg .slideMain
{width:343px;height:55px;margin-left:26px;overflow:hidden;position:relative;}
.littleImg .slideMain ul
{position:absolute;left:0;width:355px;padding-top:1px;}
.littleImg .slideMain ul li
{float:left;margin-right:6px;cursor:pointer;width:50px;height:50px;border:1px
solid #dbdbdb;}
.littleImg .slideMain ul li.selected {border-color:#999;}
.littleImg .slideMain ul li img {float:left;width:50px;height:50px;}
/*放大镜end*/
</style>
</head>
<body>
<!–放大镜–>
<div class=”ZoomMain”>
  <div class=”zoom”>
         <span class=”move”></span>
         <img width=”393″ height=”390″  src=”1347000569971.jpg”
/>
  </div>
  <div class=”littleImg”>
       <span class=”btnL”><em></em></span>
       <span class=”btnR”><em></em></span>
        <div class=”slideMain”>
              <ul class=”clearfix”>
                <li class=”selected”><img width=”50″
height=”50″ src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000569971.jpg” medium-img=”1347000569971.jpg”
large-img=”1347000569971.jpg” /></li>
                <li><img width=”50″ height=”50″
src=”1347000590691.jpg” medium-img=”1347000590691.jpg”
large-img=”1347000590691.jpg” /></li>
              </ul>
        </div>
  </div>
  <div class=”zoomDetail”>
            <img width=”701″ height=”701″ src=”1347000569971.jpg”
/>
  </div>
</div>
<!–放大镜end–>
  

实现思路:

虚框用css中的透明度实现filter:alpha(opacity:20); opacity:0.2;

鼠标移动到小图上面时:虚框出现,大图对应出现

运行效果截图如下:

?<script type=”text/javascript”>
/**
@开发:杨永
@功能:实现细节放大,图片对应切换,自由定义css样式实现自由铺满视口等功能
@说明:基于jQ的放大镜插件,可根据需要自由调整布局来适应各种设计效果
*/
(function(){
        function Zoom(object){
               
this.zoomArea=$(“.zoom”,object);//保存促发放大效果的区域
                this.moveArea=$(“.move”,object);//保存移动区域
               
this.zoomDetail=$(“.zoomDetail”,object);//保存放大镜区域
               
this.zoomDetailImg=$(“img”,this.zoomDetail);//保存放大镜里面的图
                this.zoomAreaWidth=this.zoomArea.width();
                this.moveAreaWidth=this.moveArea.width();
                this.zoomAreaHeight=this.zoomArea.height();
                this.moveAreaHeight=this.moveArea.height();
                this.zoomDetailWidth=this.zoomDetail.width();
                this.zoomDetailHeight=this.zoomDetail.height();
               
this.zoomAreaOffset=this.zoomArea.offset();//初始化放大区域在视口中的相对偏移;
                this.XY=null;//初始化鼠标相对于放大区域的偏移偏移值
                this.moveBili=null;//
                var _this_=this;
               
this.zoomArea.mousemove(function(e){//当鼠标在放大区域移动的时候执行
                                                
_this_.move(e.pageX,e.pageY);   
                                        }).mouseover(function(){
                                            _this_.moveArea.show();
                                           
_this_.zoomDetail.show();
                                            }).mouseout(function(){
                                               
_this_.moveArea.hide();
                                               
_this_.zoomDetail.hide();                                               
                                                });
                this.calculate();//初始化并计算出需要的比例值
                //以下是小图部分的功能实现
                this.l=0;
                this.scrollObj=$(“.slideMain
ul”,object);//保存ul滚动对象
                this.lis=this.scrollObj.children();//保存小图片列表
                this.btnR=$(“.btnR”,object);//保存右边按钮
                this.btnL=$(“.btnL”,object);//保存左边边按钮
                this.lis.click(function(){
                                        _this_.changeImgSrc(this);
                                        });
               
if(this.lis.length>6){//判断图片数是否超出显示区域,是的话就注册滚动事件
                    this.s=this.lis.length-6;//获取多余出来的图片数
                   
this.scrollObj.width(60*this.lis.length+”px”);//当图片数超出默认值时,设置ul的宽度
                   
this.btnL.click(function(){_this_.scrollRight();}).mouseover(function(){$(this).addClass(“hover”)}).mouseout(function(){$(this).removeClass(“hover”);});
                   
this.btnR.click(function(){_this_.scrollLeft();}).mouseover(function(){$(this).addClass(“hover”)}).mouseout(function(){$(this).removeClass(“hover”);});;
                }
              };
        Zoom.prototype={
            scrollLeft:function(){
                if(Math.abs(this.l)==this.s){return};
                this.l–;
               
this.scrollObj.animate({left:this.l*58+”px”},”fast”);   
                },
            scrollRight:function(){
                if(this.l==0){return};
                this.l++;
                this.scrollObj.animate({left:this.l*58+”px”},”fast”);
                },
            changeImgSrc:function(o){
                //改变标识样式
               
$(o).addClass(“selected”).siblings().removeClass(“selected”);
               
this.zoomArea.find(“img”).attr(“src”,$(o).find(“img”).attr(“medium-img”));
               
this.zoomDetailImg.attr(“src”,$(o).find(“img”).attr(“medium-img”));

?<script type=”text/javascript”>
/**
@开发:杨永
@功能:实现细节放大,图片对应切换,自由定义css样式实现自由铺满视口等功能
@说明:基于jQ的放大镜插件,可根据需要自由调整布局来适应各种设计效果
*/
(function(){
        function Zoom(object){
               
this.zoomArea=$(“.zoom”,object);//保存促发放大效果的区域
                this.moveArea=$(“.move”,object);//保存移动区域
               
this.zoomDetail=$(“.zoomDetail”,object);//保存放大镜区域
               
this.zoomDetailImg=$(“img”,this.zoomDetail);//保存放大镜里面的图
                this.zoomAreaWidth=this.zoomArea.width();
                this.moveAreaWidth=this.moveArea.width();
                this.zoomAreaHeight=this.zoomArea.height();
                this.moveAreaHeight=this.moveArea.height();
                this.zoomDetailWidth=this.zoomDetail.width();
                this.zoomDetailHeight=this.zoomDetail.height();
               
this.zoomAreaOffset=this.zoomArea.offset();//初始化放大区域在视口中的相对偏移;
                this.XY=null;//初始化鼠标相对于放大区域的偏移偏移值
                this.moveBili=null;//
                var _this_=this;
               
this.zoomArea.mousemove(function(e){//当鼠标在放大区域移动的时候执行
                                                
_this_.move(e.pageX,e.pageY);   
                                        }).mouseover(function(){
                                            _this_.moveArea.show();
                                           
_this_.zoomDetail.show();
                                            }).mouseout(function(){
                                               
_this_.moveArea.hide();
                                               
_this_.zoomDetail.hide();                                               
                                                });
                this.calculate();//初始化并计算出需要的比例值
                //以下是小图部分的功能实现
                this.l=0;
                this.scrollObj=$(“.slideMain
ul”,object);//保存ul滚动对象
                this.lis=this.scrollObj.children();//保存小图片列表
                this.btnR=$(“.btnR”,object);//保存右边按钮
                this.btnL=$(“.btnL”,object);//保存左边边按钮
                this.lis.click(function(){
                                        _this_.changeImgSrc(this);
                                        });
               
if(this.lis.length>6){//判断图片数是否超出显示区域,是的话就注册滚动事件
                    this.s=this.lis.length-6;//获取多余出来的图片数
                   
this.scrollObj.width(60*this.lis.length+”px”);//当图片数超出默认值时,设置ul的宽度
                   
this.btnL.click(function(){_this_.scrollRight();}).mouseover(function(){$(this).addClass(“hover”)}).mouseout(function(){$(this).removeClass(“hover”);});
                   
this.btnR.click(function(){_this_.scrollLeft();}).mouseover(function(){$(this).addClass(“hover”)}).mouseout(function(){$(this).removeClass(“hover”);});;
                }
              };
        Zoom.prototype={
            scrollLeft:function(){
                if(Math.abs(this.l)==this.s){return};
                this.l–;
               
this.scrollObj.animate({left:this.l*58+”px”},”fast”);   
                },
            scrollRight:function(){
                if(this.l==0){return};
                this.l++;
                this.scrollObj.animate({left:this.l*58+”px”},”fast”);
                },
            changeImgSrc:function(o){
                //改变标识样式
               
$(o).addClass(“selected”).siblings().removeClass(“selected”);
               
this.zoomArea.find(“img”).attr(“src”,$(o).find(“img”).attr(“medium-img”));
               
this.zoomDetailImg.attr(“src”,$(o).find(“img”).attr(“medium-img”));

细节注意的地方:

1:虚框的定位:保持鼠标位于虚框的中心,如何处理鼠标中心距离四边距离小于虚框半径(或者方形的边长的一半)的情况?

2:保持大图中显示的内容是虚框选中的内容(保持大小图的比例问题)

代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>js_study</title>
    <meta  content="text/html;charset=utf-8" http-equiv="Content-Type">
    <script src="js_study.js" type="text/javascript" charset="utf-8"></script>
<style>
    #div1 { width:280px; height:200px; position:relative; margin:30px auto 0px;}
    #div1 img{width:280px; height:200px;}
    #div1 span { width:100px; height:100px; background:blue; left:0px;top:0px; position:absolute; display:none; filter:alpha(opacity:20); opacity:0.2;}
    .show { width:100%; height:100%; background:blue; position:absolute; z-index:10px; filter:alpha(opacity:10); opacity:0.1; left:0px; top:0px; }
    #div2 {width:400px; height:400px; position:relative; display:none; overflow:hidden; margin:0px auto 0px;}
    #img1 { position:absolute;}
</style>
</head>
<body style="margin 0px; text-align: center" onload="init();" >
        <div id="div1">
            <img src="./num/2.jpg">

            <div class="show"></div>
        </div>
        <div id="div2" style="display: none;">
            <img id="img1" src="./num/2.jpg" style="left: -610px; top: -149.21311475409834px;">
        </div>
</body>
</html>

 

//放大镜效果
var moveme = false;
function init () {
    var d1 = document.getElementById('div1');
    var the_float = d1.getElementsByTagName('div')[0];
    var the_span  = d1.getElementsByTagName('span')[0];
    var the_img   = document.getElementById('img1');
    the_float.onmouseover = function  () {
        the_span.style.display = 'block';
        the_img.parentNode.style.display = 'block';
    }
    the_float.onmouseout  = function  () {
        the_span.style.display = 'none';
        the_img.parentNode.style.display = 'none';
    }
    the_float.onmousemove = function  (ev) {
        var oEvent = ev||window.event;
        var x = oEvent.clientX - d1.offsetLeft - the_span.offsetWidth/2;//鼠标横坐标-父块距离浏览器窗口左距离-虚框的半
        var y = oEvent.clientY - d1.offsetTop - the_span.offsetHeight/2;
        //小图区域
        if(x<0) x=0;//左边界
        else if(x>the_float.offsetWidth - the_span.offsetWidth)//右边界
            x = the_float.offsetWidth - the_span.offsetWidth;
        if(y<0) y= 0;//上边界
        else if(y>the_float.offsetHeight - the_span.offsetHeight)//下边界
            y = the_float.offsetHeight -the_span.offsetHeight;
        the_span.style.left  = x+"px";
        the_span.style.top   = y+"px";
        //大图对应区域
        var percentX = x/(the_float.offsetWidth - the_span.offsetWidth);//计算比例
        var percentY = y/(the_float.offsetHeight - the_span.offsetHeight);
        var iParent = the_img.parentNode;
        //保持大小图之间的比例关系
        the_img.style.width = parseFloat(the_float.offsetWidth)/parseFloat(the_span.offsetWidth)*parseFloat(iParent.offsetWidth)+"px";
        the_img.style.left = -percentX*(the_img.offsetWidth - iParent.offsetWidth)+"px";
        the_img.style.top  = -percentY*(the_img.offsetHeight - iParent.offsetHeight)+"px";
    }
}

 

图片 4

                },
            move:function(x,y){//鼠标在放大区域移动的时候执行的函数
                   
this.XY=this.mousePosAndSetPos(x,y);//计算出鼠标相对于放大区域的x,y值
                    //设置滑块的位置
                    this.moveArea.css({
                                      left:this.XY.offsetX+”px”,
                                      top:this.XY.offsetY+”px”
                                      });
                    //设置大图在细节位置
                    this.zoomDetailImg.css({
                                          
marginLeft:-this.XY.offsetX*this.moveBili+”px”,
                                          
marginTop:-this.XY.offsetY*this.moveBili+”px”
                                           });
                },
            mousePosAndSetPos:function(x,y){//实时计算并设置滑块的位置
                x=x-this.zoomAreaOffset.left-this.moveArea.width()/2;
                y=y-this.zoomAreaOffset.top-this.moveArea.height()/2;
                x=x<0?0:x;
                y=y<0?0:y;
               
x=x>(this.zoomAreaWidth-this.moveAreaWidth)?this.zoomAreaWidth-this.moveAreaWidth:x;
               
y=y>(this.zoomAreaHeight-this.moveAreaHeight)?this.zoomAreaHeight-this.moveAreaHeight:y;
                return {
                        offsetX:x,
                        offsetY:y
                        };  
                },
            calculate:function(){//计算函数
                    var widthBili,heightBili;
                    //计算移动的滑块与放大镜铺面显示的比例宽高
                   
widthBili=(this.zoomAreaWidth*this.zoomDetailWidth)/this.moveAreaWidth;
                   
heightBili=(this.zoomAreaHeight*this.zoomDetailHeight)/this.moveAreaHeight;
                    //把比出来的宽高
                   
this.zoomDetailImg.css({width:widthBili+”px”,height:heightBili+”px”});
                    //返回移动的比例
                   
this.moveBili=(widthBili-this.zoomDetailWidth)/(this.zoomAreaWidth-this.moveAreaWidth);
                }
            };
          var zoom=new Zoom($(“.ZoomMain”).eq(0));    
})();

                },
            move:function(x,y){//鼠标在放大区域移动的时候执行的函数
                   
this.XY=this.mousePosAndSetPos(x,y);//计算出鼠标相对于放大区域的x,y值
                    //设置滑块的位置
                    this.moveArea.css({
                                      left:this.XY.offsetX+”px”,
                                      top:this.XY.offsetY+”px”
                                      });
                    //设置大图在细节位置
                    this.zoomDetailImg.css({
                                          
marginLeft:-this.XY.offsetX*this.moveBili+”px”,
                                          
marginTop:-this.XY.offsetY*this.moveBili+”px”
                                           });
                },
            mousePosAndSetPos:function(x,y){//实时计算并设置滑块的位置
                x=x-this.zoomAreaOffset.left-this.moveArea.width()/2;
                y=y-this.zoomAreaOffset.top-this.moveArea.height()/2;
                x=x<0?0:x;
                y=y<0?0:y;
               
x=x>(this.zoomAreaWidth-this.moveAreaWidth)?this.zoomAreaWidth-this.moveAreaWidth:x;
               
y=y>(this.zoomAreaHeight-this.moveAreaHeight)?this.zoomAreaHeight-this.moveAreaHeight:y;
                return {
                        offsetX:x,
                        offsetY:y
                        };  
                },
            calculate:function(){//计算函数
                    var widthBili,heightBili;
                    //计算移动的滑块与放大镜铺面显示的比例宽高
                   
widthBili=(this.zoomAreaWidth*this.zoomDetailWidth)/this.moveAreaWidth;
                   
heightBili=(this.zoomAreaHeight*this.zoomDetailHeight)/this.moveAreaHeight;
                    //把比出来的宽高
                   
this.zoomDetailImg.css({width:widthBili+”px”,height:heightBili+”px”});
                    //返回移动的比例
                   
this.moveBili=(widthBili-this.zoomDetailWidth)/(this.zoomAreaWidth-this.moveAreaWidth);
                }
            };
          var zoom=new Zoom($(“.ZoomMain”).eq(0));    
})();

具体代码如下:

代码如下: /*放大镜*/ .ZoomMain
{margin:100px;width:395px;height:460px;float:left;position:relative;}
.ZoomMain .zoom {height:393px;width:393px;position:relative…

您可能感兴趣的文章:

  • jquery图片放大镜效果
  • jquery实现放大镜简洁代码(推荐)
  • jQuery实现的放大镜效果示例
  • 基于jquery编写的放大镜插件
  • jQuery实现图片局部放大镜效果
  • jQuery实现放大镜效果实例代码
  • 基于jQuery仿淘宝产品图片放大镜特效
  • 基于jQuery实现放大镜效果
  • jquery实现图片放大镜功能
  • 基于jQuery仿淘宝产品图片放大镜代码分享
  • 基于jquery实现放大镜效果
  • 使用jquery实现放大镜效果
  • jquery放大镜效果超漂亮噢
  • 基于jquery的放大镜效果
  • 实现jquery放大镜的两种方法
(function () {
 $.fn.Magnifier = function (options) {

  //默认参数设置
  var settings = {
   diameter: 150,     //放大镜的直径大小
   borderWidth: 2,     //放大镜边框大小
   borderColor: "white",   //放大镜边框颜色
   backgroundImg: "../img/111.jpg" //放大镜内的图片(即大图)
  };

  //合并参数
  if (options)
   $.extend(settings, options);

  //链式原则
  return this.each(function () {
   //存储当前对象
   var root = $(this);

   //当前对象宽高
   var WRoot = root.width();
   var HRoot = root.height();

   //偏移量 left 和 top
   var offset = root.offset();

   //放大镜样式
   var style = "background-position: 0px 0px;background-repeat: no-repeat;float: left;";
   style += "position: absolute;box-shadow:0 0 5px #777, 0 0 10px #aaa inset;display: none;";
   style += "width: " + String(settings.diameter) + "px;height: " + String(settings.diameter) + "px;";
   style += "border-radius: " + String(settings.diameter / 2 + settings.borderWidth) + "px;";
   style += "border: " + String(settings.borderWidth) + "px solid " + settings.borderColor + ";";

   //创建放大镜
   var magnifier = $("<div style='" + style + "'></div>").appendTo(root.parent());

   //图片(当没有大图时,为小图本身)
   var backgroundImg = settings.backgroundImg ? settings.backgroundImg : root.attr("src");

   //将图片放入放大镜内
   magnifier.css({ backgroundImage: "url('" + backgroundImg + "')" });

   //缩放比例
   var WRatio = 0; //宽度
   var HRatio = 0; //高度

   //图片加载完,计算缩放比例
   //由于图片原本不在DOM文档里,因此页面加载时不会触发load事件,因此要通过执行appendTo来触发load事件
   $("<img style='display:none;' src='" + backgroundImg + "' />").load(function () {
    WRatio = $(this).width() / WRoot;
    HRatio = $(this).height() / HRoot;
   }).appendTo(root.parent());

   //放大镜及其背景图片位置控制
   function Position(e) {

    var LPos = parseInt(e.pageX - offset.left);
    var TPos = parseInt(e.pageY - offset.top);

    //判断鼠标是否在图片上
    if (LPos < 0 || TPos < 0 || LPos > WRoot || TPos > HRoot) {

     magnifier.hide(); //不在隐藏放大镜

    } else {

     magnifier.show(); //反之显示放大镜

     //控制放大镜内背景图片的位置 (settings.diameter / 2)半径
     LPos = String(((e.pageX - offset.left) * WRatio - settings.diameter / 2) * (-1));
     TPos = String(((e.pageY - offset.top) * HRatio - settings.diameter / 2) * (-1));

     magnifier.css({ backgroundPosition: LPos + 'px ' + TPos + 'px' });

     //控制放大镜本身位置
     LPos = String(e.pageX - settings.diameter / 2);
     TPos = String(e.pageY - settings.diameter / 2);

     magnifier.css({ left: LPos + 'px', top: TPos + 'px' });
    }
   }

   //放大镜
   magnifier.mousemove(Position);

   //当前对象
   root.mousemove(Position);

  });
 };
})();

实例DEMO如下:

<!DOCTYPE html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>CSS3+jQuery图像放大镜效果</title>
 <style type="text/css">
  body
  {
   background-color: Black;
  }
  .box
  {
   width: 700px;
   margin: 50px auto;
  }
 </style>
</head>
<body>
 <div class="box">
     <!--小图-->
  <img alt="图片 5" id="img_02" src="../img/222.gif" width="700" height="500" />
 </div>
 <script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 <script src="../Scripts/jquery.similar.magnifier.js" type="text/javascript"></script>
 <script type="text/javascript">
  $("#img_02").Magnifier();
 </script>
</body>
</html>

关于jquery实现图片放大镜功能的内容就介绍到这里,希望大家仔细研究,学以致用。

您可能感兴趣的文章:

  • jquery图片放大镜效果
  • jquery实现放大镜简洁代码(推荐)
  • jQuery实现的放大镜效果示例
  • 基于jquery编写的放大镜插件
  • jQuery实现图片局部放大镜效果
  • jQuery实现放大镜效果实例代码
  • 基于jQuery仿淘宝产品图片放大镜特效
  • 基于jQuery实现放大镜效果
  • 基于jQuery仿淘宝产品图片放大镜代码分享
  • 基于jquery实现放大镜效果
  • 使用jquery实现放大镜效果
  • jquery放大镜效果超漂亮噢
  • jquery图片放大镜功能的实例代码
  • 基于jquery的放大镜效果
  • 实现jquery放大镜的两种方法

相关文章