正如标题所说,我试图在不使用jQuery UI的情况下使div可拖动。
但是,我坚持使用下面的代码。我明白我将使用相对于容器div的鼠标位置(其中div应该被拖动),并且我将相对于这些值设置divs偏移量。
我无法弄清楚如何。有什么线索吗?
此代码(当然)不起作用:
var X, Y;
$(this).mousedown(function() {
$(this).offset({
left: X,
top: Y
});
});
$("#containerDiv").mousemove(function(event) {
X = event.pageX;
Y = event.pageY;
});
答案 0 :(得分:74)
这是一个真正的简单示例,可以帮助您入门:
$(document).ready(function() {
var $dragging = null;
$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY,
left: e.pageX
});
}
});
$(document.body).on("mousedown", "div", function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
});
示例: http://jsfiddle.net/Jge9z/
据我所知,我将使用相对于容器div的鼠标位置(div应该被拖动),并且我将相对于这些值设置divs偏移量。
不太确定。在我看来,在拖放时你总是 想要使用元素相对于文档的偏移量。
如果您的意思是想要将拖动限制在特定区域,那么这是一个更复杂的问题(但仍然可行)。
答案 1 :(得分:42)
这是另一个更新的代码:
$(document).ready(function() {
var $dragging = null;
$('body').on("mousedown", "div", function(e) {
$(this).attr('unselectable', 'on').addClass('draggable');
var el_w = $('.draggable').outerWidth(),
el_h = $('.draggable').outerHeight();
$('body').on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY - el_h / 2,
left: e.pageX - el_w / 2
});
}
});
$dragging = $(e.target);
}).on("mouseup", ".draggable", function(e) {
$dragging = null;
$(this).removeAttr('unselectable').removeClass('draggable');
});
});
演示: http://jsfiddle.net/tovic/Jge9z/31/
我为这个帖子创建了一个简单的插件。
// Simple JQuery Draggable Plugin
// https://plus.google.com/108949996304093815163/about
// Usage: $(selector).drags();
// Options:
// handle => your dragging handle.
// If not defined, then the whole body of the
// selected element will be draggable
// cursor => define your draggable element cursor type
// draggableClass => define the draggable class
// activeHandleClass => define the active handle class
//
// Update: 26 February 2013
// 1. Move the `z-index` manipulation from the plugin to CSS declaration
// 2. Fix the laggy effect, because at the first time I made this plugin,
// I just use the `draggable` class that's added to the element
// when the element is clicked to select the current draggable element. (Sorry about my bad English!)
// 3. Move the `draggable` and `active-handle` class as a part of the plugin option
// Next update?? NEVER!!! Should create a similar plugin that is not called `simple`!
(function($) {
$.fn.drags = function(opt) {
opt = $.extend({
handle: "",
cursor: "move",
draggableClass: "draggable",
activeHandleClass: "active-handle"
}, opt);
var $selected = null;
var $elements = (opt.handle === "") ? this : this.find(opt.handle);
$elements.css('cursor', opt.cursor).on("mousedown", function(e) {
if(opt.handle === "") {
$selected = $(this);
$selected.addClass(opt.draggableClass);
} else {
$selected = $(this).parent();
$selected.addClass(opt.draggableClass).find(opt.handle).addClass(opt.activeHandleClass);
}
var drg_h = $selected.outerHeight(),
drg_w = $selected.outerWidth(),
pos_y = $selected.offset().top + drg_h - e.pageY,
pos_x = $selected.offset().left + drg_w - e.pageX;
$(document).on("mousemove", function(e) {
$selected.offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
});
}).on("mouseup", function() {
$(this).off("mousemove"); // Unbind events from document
if ($selected !== null) {
$selected.removeClass(opt.draggableClass);
$selected = null;
}
});
e.preventDefault(); // disable selection
}).on("mouseup", function() {
if(opt.handle === "") {
$selected.removeClass(opt.draggableClass);
} else {
$selected.removeClass(opt.draggableClass)
.find(opt.handle).removeClass(opt.activeHandleClass);
}
$selected = null;
});
return this;
};
})(jQuery);
演示: http://tovic.github.io/dte-project/jquery-draggable/index.html
答案 2 :(得分:13)
这是我的贡献:
http://jsfiddle.net/g6m5t8co/1/
<!doctype html>
<html>
<head>
<style>
#container {
position:absolute;
background-color: blue;
}
#elem{
position: absolute;
background-color: green;
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
-khtml-user-select: none;
user-select: none;
}
</style>
<script>
var mydragg = function(){
return {
move : function(divid,xpos,ypos){
divid.style.left = xpos + 'px';
divid.style.top = ypos + 'px';
},
startMoving : function(divid,container,evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
divTop = divid.style.top,
divLeft = divid.style.left,
eWi = parseInt(divid.style.width),
eHe = parseInt(divid.style.height),
cWi = parseInt(document.getElementById(container).style.width),
cHe = parseInt(document.getElementById(container).style.height);
document.getElementById(container).style.cursor='move';
divTop = divTop.replace('px','');
divLeft = divLeft.replace('px','');
var diffX = posX - divLeft,
diffY = posY - divTop;
document.onmousemove = function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
aX = posX - diffX,
aY = posY - diffY;
if (aX < 0) aX = 0;
if (aY < 0) aY = 0;
if (aX + eWi > cWi) aX = cWi - eWi;
if (aY + eHe > cHe) aY = cHe -eHe;
mydragg.move(divid,aX,aY);
}
},
stopMoving : function(container){
var a = document.createElement('script');
document.getElementById(container).style.cursor='default';
document.onmousemove = function(){}
},
}
}();
</script>
</head>
<body>
<div id='container' style="width: 600px;height: 400px;top:50px;left:50px;">
<div id="elem" onmousedown='mydragg.startMoving(this,"container",event);' onmouseup='mydragg.stopMoving("container");' style="width: 200px;height: 100px;">
<div style='width:100%;height:100%;padding:10px'>
<select id=test>
<option value=1>first
<option value=2>second
</select>
<INPUT TYPE=text value="123">
</div>
</div>
</div>
</body>
</html>
答案 3 :(得分:8)
这是制作一个以点击为中心的可拖动对象的另一种方法
http://jsfiddle.net/pixelass/fDcZS/
function endMove() {
$(this).removeClass('movable');
}
function startMove() {
$('.movable').on('mousemove', function(event) {
var thisX = event.pageX - $(this).width() / 2,
thisY = event.pageY - $(this).height() / 2;
$('.movable').offset({
left: thisX,
top: thisY
});
});
}
$(document).ready(function() {
$("#containerDiv").on('mousedown', function() {
$(this).addClass('movable');
startMove();
}).on('mouseup', function() {
$(this).removeClass('movable');
endMove();
});
});
CSS
#containerDiv {
background:#333;
position:absolute;
width:200px;
height:100px;
}
答案 4 :(得分:6)
像jQueryUI一样拖动:JsFiddle
您可以从任何点拖动元素,而不会出现奇怪的居中。
$(document).ready(function() {
var $body = $('body');
var $target = null;
var isDraggEnabled = false;
$body.on("mousedown", "div", function(e) {
$this = $(this);
isDraggEnabled = $this.data("draggable");
if (isDraggEnabled) {
if(e.offsetX==undefined){
x = e.pageX-$(this).offset().left;
y = e.pageY-$(this).offset().top;
}else{
x = e.offsetX;
y = e.offsetY;
};
$this.addClass('draggable');
$body.addClass('noselect');
$target = $(e.target);
};
});
$body.on("mouseup", function(e) {
$target = null;
$body.find(".draggable").removeClass('draggable');
$body.removeClass('noselect');
});
$body.on("mousemove", function(e) {
if ($target) {
$target.offset({
top: e.pageY - y,
left: e.pageX - x
});
};
});
});
答案 5 :(得分:5)
最基本的可拖动代码是:
Element.prototype.drag = function(){
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
}.bind(this);
this.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
}.bind(this));
this.style.position = 'absolute' // fixed might work as well
}
然后使用(非jquery):
document.querySelector('.target').drag();
或在jquery中:
$('.target')[0].drag();
注意:拖动的元素应该有position:absolute
或position:fixed
应用于左侧,顶部移动才能工作...
下面的codepen还有一些&#34; advanced&#34;功能:dragStart,dragStop回调,css类追加拖动时删除其他元素的文本选择,还有一个拖放功能...
签出以下codepen:
http://codepen.io/anon/pen/VPPaEK
它基本上设置了一个'mousedown&#39;需要拖动的元素上的事件,然后绑定和解除文档鼠标移动以处理移动。
为元素设置可拖动句柄
Element.prototype.drag = function( setup ){
var setup = setup || {};
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
}.bind(this);
var handle = setup.handle || this;
handle.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
handle.classList.add('dragging');
}.bind(this));
handle.classList.add('draggable');
this.style.position = 'absolute' // fixed might work as well
}
以上代码的使用方式如下:
var setup = {
handle : document.querySelector('.handle')
};
document.querySelector('.box').drag(setup);
现在的问题是,当拖动时,可拖动元素中的文本被令人烦恼地选中而没有用...
这就是为什么我们已将draggable
和dragging
类添加到元素中。这将取消这种不需要的行为,并添加一个移动光标,以显示该元素是可拖动的
.draggable{
cursor: move;
position: fixed;
}
.draggable.dragging{
user-select: none;
}
现在我们有了可拖动的元素,我们有时需要调用各种事件。
setup.ondraginit // this is called when setting up the draggable
setup.ondragstart // this is called when mouse is down on the element
setup.ondragend // this is called when mouse is released (after dragging)
setup.ondrag // this is called while the element is being dragged
每个都会将原始鼠标事件传递给特定处理程序
最后,这就是我们得到的......
Element.prototype.drag = function( setup ){
var setup = setup || {};
var mousemove = function(e){ // document mousemove
this.style.left = ( e.clientX - this.dragStartX ) + 'px';
this.style.top = ( e.clientY - this.dragStartY ) + 'px';
setup.ondrag && setup.ondrag(e); // ondrag event
}.bind(this);
var mouseup = function(e){ // document mouseup
document.removeEventListener('mousemove',mousemove);
document.removeEventListener('mouseup',mouseup);
handle.classList.remove('dragging');
setup.ondragend && setup.ondragend(e); // ondragend event
}.bind(this);
var handle = setup.handle || this;
handle.addEventListener('mousedown',function(e){ // element mousedown
this.dragStartX = e.offsetX;
this.dragStartY = e.offsetY;
document.addEventListener('mousemove',mousemove);
document.addEventListener('mouseup',mouseup);
handle.classList.add('dragging');
setup.ondragstart && setup.ondragstart(e); // ondragstart event
}.bind(this));
handle.classList.add('draggable');
setup.ondraginit && setup.ondraginit(e); // ondraginit event
}
并使用它:
var setup = {
handle : document.querySelector('.handle'),
ondragstart : e => { console.log('drag has started!'); },
ondrag : e => { console.log('drag!'); },
ondragend : e => { console.log('drag has ended!'); }
};
document.querySelector('.box').drag(setup);
请注意e.target
是对我们的可拖动元素的引用
答案 6 :(得分:4)
这是我的。 http://jsfiddle.net/pd1vojsL/
div中的3个可拖动按钮,拖动受div限制。
<div id="parent" class="parent">
<button id="button1" class="button">Drag me</button>
<button id="button2" class="button">Drag me</button>
<button id="button3" class="button">Drag me</button>
</div>
<div id="log1"></div>
<div id="log2"></div>
需要JQuery(仅限):
$(function() {
$('.button').mousedown(function(e) {
if(e.which===1) {
var button = $(this);
var parent_height = button.parent().innerHeight();
var top = parseInt(button.css('top')); //current top position
var original_ypos = button.css('top','').position().top; //original ypos (without top)
button.css({top:top+'px'}); //restore top pos
var drag_min_ypos = 0-original_ypos;
var drag_max_ypos = parent_height-original_ypos-button.outerHeight();
var drag_start_ypos = e.clientY;
$('#log1').text('mousedown top: '+top+', original_ypos: '+original_ypos);
$(window).on('mousemove',function(e) {
//Drag started
button.addClass('drag');
var new_top = top+(e.clientY-drag_start_ypos);
button.css({top:new_top+'px'});
if(new_top<drag_min_ypos) { button.css({top:drag_min_ypos+'px'}); }
if(new_top>drag_max_ypos) { button.css({top:drag_max_ypos+'px'}); }
$('#log2').text('mousemove min: '+drag_min_ypos+', max: '+drag_max_ypos+', new_top: '+new_top);
//Outdated code below (reason: drag contrained too early)
/*if(new_top>=drag_min_ypos&&new_top<=drag_max_ypos) {
button.css({top:new_top+'px'});
}*/
});
$(window).on('mouseup',function(e) {
if(e.which===1) {
//Drag finished
$('.button').removeClass('drag');
$(window).off('mouseup mousemove');
$('#log1').text('mouseup');
$('#log2').text('');
}
});
}
});
});
答案 7 :(得分:2)
我在上面看到的很复杂.....
这里有一些代码可以参考。
$("#box").on({
mousedown:function(e)
{
dragging = true;
dragX = e.clientX - $(this).position().left;
//To calculate the distance between the cursor pointer and box
dragY = e.clientY - $(this).position().top;
},
mouseup:function(){dragging = false;},
//If not set this on/off,the move will continue forever
mousemove:function(e)
{
if(dragging)
$(this).offset({top:e.clientY-dragY,left:e.clientX-dragX});
}
})
dragging,dragX,dragY可以放置为全局变量。
这是关于此问题的简单展示,但是有关此方法有一些错误。
如果现在需要,这里是Example here.
答案 8 :(得分:0)
$(document).ready(function() {
var $startAt = null;
$(document.body).live("mousemove", function(e) {
if ($startAt) {
$("#someDiv").offset({
top: e.pageY,
left: $("#someDiv").position().left-$startAt+e.pageX
});
$startAt = e.pageX;
}
});
$("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;});
$(document.body).live("mouseup", function (e) {$startAt = null;});
});
答案 9 :(得分:-1)
这是我的简单版本 函数draggable将jQuery对象作为参数。
/**
* @param {jQuery} elem
*/
function draggable(elem){
elem.mousedown(function(evt){
var x = parseInt(this.style.left || 0) - evt.pageX;
var y = parseInt(this.style.top || 0) - evt.pageY;
elem.mousemove(function(evt){
elem.css('left', x + evt.pageX);
elem.css('top', y + evt.pageY);
});
});
elem.mouseup(off);
elem.mouseleave(off);
function off(){
elem.off("mousemove");
}
}
答案 10 :(得分:-2)
这是一个完全没有使用jQuery的实现 -
http://thezillion.wordpress.com/2012/09/27/javascript-draggable-2-no-jquery
在您的HTML代码中嵌入JS文件(http://zillionhost.xtreemhost.com/tzdragg/tzdragg.js),并输入以下代码 -
<script>
win.onload = function(){
tzdragg.drag('elem1, elem2, ..... elemn');
// ^ IDs of the draggable elements separated by a comma.
}
</script>
代码也很容易学习 http://thezillion.wordpress.com/2012/08/29/javascript-draggable-no-jquery