不要拖过 window 条边
Don't drag over window edges
我有两个相互重叠的 div。
.second 在 .first 之上。
每个都占用完整的 window 宽度和高度。
.second 的 属性
position: absolute; left: -800px;
这样您就可以单击它的一部分将其拖到 .first
我想要拖动功能来防止 .second 超出框架的右边缘 and/or 比左边 -800px 更远。
下面是一个示例,说明如何将 jquery ui 的包含选项与数组一起拖动。该数组采用 4 个数字,其中前 2 个数字定义边界框的左上角,最后 2 个数字定义边界框的右下角。
因此在下面的示例中,元素左侧的最小 css 是 0px
,最大 css 左侧是 400px
。最小 css 顶部是 10px
,最大 css 顶部是 200px
。
基本上您只需要根据需要调整数组中的值。
var index1 = 10;
$('#test').draggable({
containment: [0, index1, $('body').width()/4, 200]
});
// update option containment after a window resize
$(window).resize(function() {
$( "#test" ).draggable( "option", "containment", "parent" );
});
body{
height: 350px;
}
#test{
width: 50px;
height: 50px;
border: 2px solid #000;
background: gray;
position: absolute;
top: 10px;
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="test"></div>
我有两个相互重叠的 div。 .second 在 .first 之上。 每个都占用完整的 window 宽度和高度。
.second 的 属性
position: absolute; left: -800px;
这样您就可以单击它的一部分将其拖到 .first
我想要拖动功能来防止 .second 超出框架的右边缘 and/or 比左边 -800px 更远。
下面是一个示例,说明如何将 jquery ui 的包含选项与数组一起拖动。该数组采用 4 个数字,其中前 2 个数字定义边界框的左上角,最后 2 个数字定义边界框的右下角。
因此在下面的示例中,元素左侧的最小 css 是 0px
,最大 css 左侧是 400px
。最小 css 顶部是 10px
,最大 css 顶部是 200px
。
基本上您只需要根据需要调整数组中的值。
var index1 = 10;
$('#test').draggable({
containment: [0, index1, $('body').width()/4, 200]
});
// update option containment after a window resize
$(window).resize(function() {
$( "#test" ).draggable( "option", "containment", "parent" );
});
body{
height: 350px;
}
#test{
width: 50px;
height: 50px;
border: 2px solid #000;
background: gray;
position: absolute;
top: 10px;
left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="test"></div>