jQuery 可拖动。全尺寸图像是否可以拖动到 body 范围内的边界?
jQuery draggable. Fullsize image draggable to its boundries within body?
可能是一个简单的任务,但我不知道如何处理它。
我有一张巨大的图片(图片是动态的,具有不同的宽度和高度),我希望它始终在我的页面上以垂直居中和水平居中的方式加载。
图像总是太大,body 无法覆盖它,所以它会溢出页面,但这正是我想要和需要的。
任务 1.)
我只需要自动将它定位在图像的中心始终垂直和水平居中在 body.
内
任务 2.)
我希望图像可以拖动,但要精确到它的边界。
所以我希望图像被拖动直到我到达右上角并且它到达视口的角落,但我不希望它可以进一步拖动。
-> http://jsfiddle.net/3j40b4u1/
<div class="container">
<img class="draggable" src="http://upload.wikimedia.org/wikipedia/commons/b/ba/Flower_jtca001.jpg" alt="image"/>
</div>
所以这应该是不可能的……https://s3.amazonaws.com/f.cl.ly/items/3p2P222S2d163N1R0v2M/Screen%20Shot%202015-03-04%20at%2018.53.47.png
我该怎么做?
提前致谢,
马特
实现起来并不那么简单,但让我们试试吧。首先我们需要向我们的 "drag" 事件注入代码,我们强制它不要超出我们的边界:
drag : function(e,ui) {
//Force the helper position
if (ui.position.left > 0) {
ui.position.left = 0;
}
if (ui.position.top > 0) {
ui.position.top = 0;
}
}
然后是第二部分,居中图像。您可以通过多种方式实现它 - 您只需要记住在我们的可拖动方法的 "create" 事件上调用它:
create: function (event, ui) {
var img = $(".draggable")
, imgWidth = img.width()
, imgHeight = img.height();
img.css("position","absolute");
img.css("top", Math.min(0, ($(window).height() - imgWidth / 2) +
$(window).scrollTop()) + "px");
img.css("left", Math.min(0, ($(window).width() - imgHeight / 2) +
$(window).scrollLeft()) + "px");
}
到此为止!没那么复杂。
可能是一个简单的任务,但我不知道如何处理它。
我有一张巨大的图片(图片是动态的,具有不同的宽度和高度),我希望它始终在我的页面上以垂直居中和水平居中的方式加载。
图像总是太大,body 无法覆盖它,所以它会溢出页面,但这正是我想要和需要的。
任务 1.) 我只需要自动将它定位在图像的中心始终垂直和水平居中在 body.
内任务 2.) 我希望图像可以拖动,但要精确到它的边界。 所以我希望图像被拖动直到我到达右上角并且它到达视口的角落,但我不希望它可以进一步拖动。
-> http://jsfiddle.net/3j40b4u1/
<div class="container">
<img class="draggable" src="http://upload.wikimedia.org/wikipedia/commons/b/ba/Flower_jtca001.jpg" alt="image"/>
</div>
所以这应该是不可能的……https://s3.amazonaws.com/f.cl.ly/items/3p2P222S2d163N1R0v2M/Screen%20Shot%202015-03-04%20at%2018.53.47.png
我该怎么做?
提前致谢, 马特
实现起来并不那么简单,但让我们试试吧。首先我们需要向我们的 "drag" 事件注入代码,我们强制它不要超出我们的边界:
drag : function(e,ui) {
//Force the helper position
if (ui.position.left > 0) {
ui.position.left = 0;
}
if (ui.position.top > 0) {
ui.position.top = 0;
}
}
然后是第二部分,居中图像。您可以通过多种方式实现它 - 您只需要记住在我们的可拖动方法的 "create" 事件上调用它:
create: function (event, ui) {
var img = $(".draggable")
, imgWidth = img.width()
, imgHeight = img.height();
img.css("position","absolute");
img.css("top", Math.min(0, ($(window).height() - imgWidth / 2) +
$(window).scrollTop()) + "px");
img.css("left", Math.min(0, ($(window).width() - imgHeight / 2) +
$(window).scrollLeft()) + "px");
}
到此为止!没那么复杂。