【发布时间】:2016-08-13 01:28:42
【问题描述】:
我正在开发缩放功能。此缩放是一个固定框,具有 100% 的窗口大小,并且在一个具有固定框宽度的 200% 的图像内。
这个缩放需要像这样工作:
- 当光标在窗口中心时,图像应该在中心。
- 当光标在右上角时,图像应该停留在窗口的右上角(这样才能到达有角的图像)
- 当光标在中下角时,图像应该水平居中并到达总底部,这样我们就可以看到图像的中底部分。
- 等等。
我接近了,但我无法完美地到达角落。这是我的 sn-p(参见 onmousemove 函数中的 cmets):
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不是更好用吗? -
我尝试在第一个实例中进行翻译,但经过一些更改,我的最终代码看起来像这样!哈哈
-
好吧,我再次将其更改为
translate(),但显然这不是问题所在。 @LGSon 我如何在这里实现纵横比? -
我稍后再看看,现在没有时间......完成后告诉你
-
没问题,我不急这个任务,只是卡住了。谢谢;)
标签: javascript jquery css aspect-ratio zooming