如何在 jQuery 中使元素可拖动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2424191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make an element draggable in jQuery?
提问by zjm1126
How do I make an element, e.g. a div, draggable using jQuery?
如何使用 jQuery 使元素(例如 div)可拖动?
采纳答案by Elzo Valugi
First load the jQuery UI:
首先加载 jQuery UI:
<link type="text/css" href="css/themename/jquery-ui-1.7.1.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script>
Then use jQuery UI draggable method:
然后使用 jQuery UI可拖动方法:
<script type="text/javascript">
$(function() {
$("#b").draggable();
});
</script>
回答by user982671
You can do with jquery only, without jquery UI:
您只能使用 jquery,而无需使用 jquery UI:
function handle_mousedown(e){
window.my_dragging = {};
my_dragging.pageX0 = e.pageX;
my_dragging.pageY0 = e.pageY;
my_dragging.elem = this;
my_dragging.offset0 = $(this).offset();
function handle_dragging(e){
var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
$(my_dragging.elem)
.offset({top: top, left: left});
}
function handle_mouseup(e){
$('body')
.off('mousemove', handle_dragging)
.off('mouseup', handle_mouseup);
}
$('body')
.on('mouseup', handle_mouseup)
.on('mousemove', handle_dragging);
}
$('#b').mousedown(handle_mousedown);
回答by Jason Sebring
I just cooked this up so its very portable instead of "dragging" in the whole jQuery UI.
我刚刚做了这个,所以它非常便携,而不是在整个 jQuery UI 中“拖动”。
It doesn't select text when dragging below it so this actually works in production unlike the other code here.
它在拖动到文本下方时不会选择文本,因此与此处的其他代码不同,这实际上可以在生产中使用。
This also works with fixed positioned elements quite nicely so you can "dock"
这也很好地适用于固定定位的元素,因此您可以“停靠”
$.fn.draggable = function(){
var $this = this,
ns = 'draggable_'+(Math.random()+'').replace('.',''),
mm = 'mousemove.'+ns,
mu = 'mouseup.'+ns,
$w = $(window),
isFixed = ($this.css('position') === 'fixed'),
adjX = 0, adjY = 0;
$this.mousedown(function(ev){
var pos = $this.offset();
if (isFixed) {
adjX = $w.scrollLeft(); adjY = $w.scrollTop();
}
var ox = (ev.pageX - pos.left), oy = (ev.pageY - pos.top);
$this.data(ns,{ x : ox, y: oy });
$w.on(mm, function(ev){
ev.preventDefault();
ev.stopPropagation();
if (isFixed) {
adjX = $w.scrollLeft(); adjY = $w.scrollTop();
}
var offset = $this.data(ns);
$this.css({left: ev.pageX - adjX - offset.x, top: ev.pageY - adjY - offset.y});
});
$w.on(mu, function(){
$w.off(mm + ' ' + mu).removeData(ns);
});
});
return this;
};
But this assumes absolute or fixed positioning is applied to the element already.
但这假设绝对或固定定位已经应用于元素。
Use it like so:
像这样使用它:
$('#something').draggable();