这是我不久前编写的一些代码,用于“缩放”幻灯片的缩略图:
$(function () {
$('#container-id').bind('mousewheel', function (event, delta) {
event.preventDefault();
var sc = $.data(this, 'scale');
if ((delta == 1 && sc < 5) || (delta == -1 && sc > 1)) {
sc += delta;
$.data(this, 'scale', sc);
$(this).find('img').css({
WebkitTransform : 'scale(' + sc + ')',
MozTransform : 'scale(' + sc + ')',
MsTransform : 'scale(' + sc + ')',
OTransform : 'scale(' + sc + ')',
Transform : 'scale(' + sc + ')'
});
}
}).bind('mousemove', function (event) {
//only run the code if the thumbnail is zoomed in, otherwise there is no point in doing these calculations
var sc = $.data(this, 'scale') || 1;//scale
if (sc > 1) {
var $this = $(this),
X = (typeof(event.offsetX) == 'undefined') ? (event.pageX - $this.offset().left) : (event.offsetX),//current cursor X position in bullet element
Y = (typeof(event.offsetY) == 'undefined') ? (event.pageY - $this.offset().top) : (event.offsetY),//current cursor Y position in bullet element
w = 100,//width of a thumbnail
h = 100,//height of a thumbnail
nX = ((w / 2) - X),//new X
nY = ((h / 2) - Y),//new Y
tf = 'translate(' + (nX * (sc - 1)) + 'px, ' + (nY * (sc - 1)) + 'px) scale(' + sc + ')';//transform string
$this.find('img').css({
WebkitTransform : tf,
MozTransform : tf,
MsTransform : tf,
OTransform : tf,
Transform : tf
});
}
}).bind('mouseleave', function () {
//reset .has-thumb element on mouseleave
$.data(this, 'scale', 5);
$(this).find('.thumb-image').css({
WebkitTransform : 'translate(0, 0) scale(1)',
MozTransform : 'translate(0, 0) scale(1)',
MsTransform : 'translate(0, 0) scale(1)',
OTransform : 'translate(0, 0) scale(1)',
Transform : 'translate(0, 0) scale(1)'
});
});
$.data($('#container-id')[0], 'scale', 5);
});
示例 HTML 如下所示:
<div id="container-id">
<img src="..." />
</div>
还有一些 CSS 来总结一下:
#container-id {
width : 100px;
height : 100px;
overflow : hidden;
}
#container-id img {
width : 100px;
height : 100px;
}
这是一个演示:http://jsfiddle.net/Bbsze/1/
如果您对此代码感兴趣,我可以编写一些文档以使其更加清晰。另请注意,此代码利用 CSS3 transform 属性,因此旧浏览器需要更多代码。