jQuery UI 可拖动 - 当内部元素大于父元素时,将内部元素限制在父元素内
我正在尝试使用 jQuery UI 实现这种效果 - 非常类似于在 Facebook 上裁剪图像的方式:
http://blog.creonfx.com/examples/javascript/facebook-cropping-mootools.html
这是一个非常简单的 HTML 测试用例(img
在 div
内):
<div>
<img src="fat_cat.jpg">
</div>
这是似乎适合该目的的逻辑 - 但它尚未完成:
$("img").draggable({ drag: dragHandler });
function dragHandler(event, ui) {
var x = event.target.x - event.target.parentNode.offsetLeft;
var y = event.target.offsetTop;
if(x > 0) {
// How to constrain the movement here?
}
if(x < -(event.target.offsetWidth -
event.target.parentNode.offsetWidth)) {
}
if(y > 0) {
}
if(y < -(event.target.offsetHeight -
event.target.parentNode.offsetHeight)) {
}
$("p").text(x + ", " + y);
}
我的第一次尝试是修改 offsetLeft
& offsetTop
变量,在所有多个访问点中,但似乎没有任何对我有用。
这是一个 jsFiddle ,其中包含上面的解释: http://jsfiddle.net/g105b/FdkBK/
I am trying to achieve this effect with jQuery UI - very much like the way you crop an image on Facebook:
http://blog.creonfx.com/examples/javascript/facebook-cropping-mootools.html
Here is a very simple test case in HTML (an img
within a div
):
<div>
<img src="fat_cat.jpg">
</div>
and here is the logic that seems fit for the purpose - however it is unfinished:
$("img").draggable({ drag: dragHandler });
function dragHandler(event, ui) {
var x = event.target.x - event.target.parentNode.offsetLeft;
var y = event.target.offsetTop;
if(x > 0) {
// How to constrain the movement here?
}
if(x < -(event.target.offsetWidth -
event.target.parentNode.offsetWidth)) {
}
if(y > 0) {
}
if(y < -(event.target.offsetHeight -
event.target.parentNode.offsetHeight)) {
}
$("p").text(x + ", " + y);
}
My first attempts were to modify the offsetLeft
& offsetTop
variables, in all their multiple access points, but nothing seems to be working for me.
Here is a jsFiddle with what is explained above: http://jsfiddle.net/g105b/FdkBK/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,您可以使用内部容器来执行此操作,其宽度/高度经过计算,仅允许图像移动一定的距离。当然,你还必须将内容器放置在适当的位置。
这是我的做法:
标记:
脚本:
You can actually do this with an inner container whose width/height is calculated to only allow the image to travel a certain distance. Of course you also have to position the inner container appropriately.
Here is my go at it:
Markup:
Script: