JavaScript: Zooming does works as intended
I suck at math so I cannot figure out what is required to make the zooming work properly. You see, when clicked for the first time, it works as intended (it zooms in to the desired position). But if you try to click more than once it won't zoom in to the desired position.
Here's the code (also provided at http://jsfiddle.net/XVmNU/)
<!DOCTYPE HTML>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
body {
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
(function ($) {
var scale = 1;
$(window).load(function () {
$('img:first').click(function (e) {
scale *= 1.5;
var w = $(this).width(),
h = $(this).height();
var new_w = w * scale,
new_h = h * scale;
var x = e.pageX,
y = e.pageY;
var new_x = Math.round(x / (w / new_w)),
new_y = Math.round(y / (h / new_h));
new_x = (0 - (new_x - x)),
new_y = (0 - (new_y - y));
$(this).animate({
left: new_x,
top: new_y,
width : new_w,
height : new_h
}, 'fast');
});
});
})(jQuery);
</script>
</head>
<body>
<img src="http://www.worldpress.org/image开发者_运维技巧s/maps/world_600w.jpg" style="position: absolute; left: 0px; top: 0px;"/>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
}
body {
overflow: hidden;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
(function ($) {
var scale = 1;
$(window).load(function () {
$('img:first').click(function (e) {
scale *= 1.5;
var w = $(this).width(),
h = $(this).height();
var new_w = w * scale,
new_h = h * scale;
var x = e.pageX,
y = e.pageY;
var new_x=Math.round([x-($(this).position().left)]*(1-scale)+$(this).position().left),
new_y=Math.round([y-($(this).position().top)]*(1-scale)+$(this).position().top);
$(this).animate({
left: new_x,
top: new_y,
width : new_w,
height : new_h
}, 'fast');
});
});
})(jQuery);
</script>
</head>
<body>
<img src="http://www.worldpress.org/images/maps/world_600w.jpg" style="position: absolute; left: 0px; top: 0px;"/>
</body>
</html>
is is something wrong with your method to compute the new_x and new_y.
精彩评论