我正在开发一个缩放功能。这个缩放是一个100%窗口大小的固定框,里面有一个200%宽度的图像。
这个缩放需要按照以下方式工作:
- 当鼠标指针在窗口中心时,图像应该在中心。 - 当鼠标指针在右上角时,图像应该停留在窗口的右上角(所以到达图像与角落)。 - 当鼠标指针在中间底部角落时,图像应该水平居中并到达底部,这样我们就可以看到图像的中间底部部分。 - 依此类推。
我已经尝试了一种方法,但无法完美地到达角落。这是我的代码片段(请参见onmousemove函数中的注释):
问题在于我使用了
我应该如何配置才能到达所有角落?为什么左边的值(像素除以2)可以完美工作,而上方的值却不能?
这个缩放需要按照以下方式工作:
- 当鼠标指针在窗口中心时,图像应该在中心。 - 当鼠标指针在右上角时,图像应该停留在窗口的右上角(所以到达图像与角落)。 - 当鼠标指针在中间底部角落时,图像应该水平居中并到达底部,这样我们就可以看到图像的中间底部部分。 - 依此类推。
我已经尝试了一种方法,但无法完美地到达角落。这是我的代码片段(请参见onmousemove函数中的注释):
var Zoom = function(imageZoom) {
this.urlImage = imageZoom;
this.img = undefined;
this.$img = undefined;
this.init = function() {
this.loaders("on");
this.calcs();
};
this.calcs = function() {
var self = this;
this.img = new Image();
this.img.onload = function() {
self.build();
};
this.img.src = this.urlImage;
};
this.loaders = function(status) {
switch(status) {
case "on":
$('#loader').fadeIn(200);
break;
case "off":
$('#loader').fadeOut(200);
break;
}
};
this.build = function() {
var self = this;
this.$img = $(self.img);
$('#zoom').fadeIn(200).append(this.$img);
this.$img.on('mousedown', function(e) {
e.preventDefault();
});
// this is the problematic function
$('body').on('mousemove', function(e) {
e.preventDefault();
// calc the percents of the window where
var px = 100 * e.pageX / $(window).width();
var py = 100 * e.pageY / $(window).height();
// calc of the percent pixel of the image
var fx = self.$img.width() * px / 100;
var fy = self.$img.height() * py / 100;
// render it left / 2 and top / 1.5 (the 1.5 value is imaginary!!)
self.$img.css({'transform': 'translate('+ -(fx/2) +'px, '+ -(fy/1.5)+'px)'});
});
self.loaders("off");
};
};
var zoom = new Zoom("http://dummyimage.com/2000x1230/000/fff");
zoom.init();
#zoom {
position: fixed;;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1000000;
display: none;
}
#zoom img {
width: 200%;
height: auto;
position: absolute;
cursor: crosshair;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loader">Loading</div>
<div id="zoom"></div>
fx/1.5
,因为fx/2
不起作用。但水平值却完美地运行。我应该如何配置才能到达所有角落?为什么左边的值(像素除以2)可以完美工作,而上方的值却不能?
translate()
,但显然那不是问题所在。 @LGSon,我如何在这里实现宽高比? - Marcos Pérez Gude