How to scale up an image as follows?
I want to scale up an image upon a mouse click so that besides scaling up the point开发者_运维技巧 of the click stays under the mouse cursor (much like Google Maps zooming). I know how to do that in CSS3, but I want to do it in JavaScript.
You'd do this with animate() and set the left/top position and width values.
Here's a demo I've written as proof of concept: http://jsfiddle.net/7PzGQ/
jQuery:
$('.imageHolder img').bind('click', function(e) {
var _this = $(this),
scale = 3;
// Store default width
if(_this.data('defWidth') == undefined) {
_this.data('defWidth', _this.width());
}
if (_this.width() > _this.data('defWidth')) {
// Reset image
_this.animate({
'left': 0,
'top': 0,
'width': _this.data('defWidth')
});
} else {
// Localise clicked position
var imgHitX = e.pageX - _this.offset().left,
imgHitY = e.pageY - _this.offset().top;
// Calculate position offset
var left = ((imgHitX * scale) - imgHitX) * -1,
top = ((imgHitY * scale) - imgHitY) * -1;
// Scale image
_this.animate({
'left': left,
'top': top,
'width': _this.width() * scale
});
}
});
HTML:
<div class="imageHolder">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif" />
</div>
CSS:
body {
background: #000;
}
.imageHolder {
position:relative;
margin: 50px;
}
.imageHolder img {
position:absolute;
left:0px;
top:0px;
}
If you could do it in CSS3, you could just use jquery's .css()
function to accomplish the same effect.
See http://api.jquery.com/css/
精彩评论