[英]How to make this jQuery function more generic (use class without losing specific positioning)
How to make this jQuery function more generic? 如何使这个jQuery函数更通用? I would prefer if #draggable was .draggable and the function could determine what .draggable was clicked, and then handle that element untill unbind.
我希望#draggable是.draggable,并且函数可以确定单击了.draggable,然后处理该元素,直到解除绑定为止。
Thanks! 谢谢!
function drag(){
$(document).bind('mousemove', function(e){
$('#draggable').css({
left: e.pageX,
top: e.pageY
});
});
};
function drop(){
$(document).unbind('mousemove');
$('#draggable').css({
left: $('.box').position().left,
top: $('.box').position().top
});
alert('Well Done! ^^')
};
<div id="draggable" onclick="drag();">
<!-- Image -->
</div>
<div class="box" onclick="drop();">
<!-- Placeholder -->
</div>
source: http://paste.ubuntu.com/794168/ 来源: http : //paste.ubuntu.com/794168/
For the first step you could add a selector function for your function parameters: 第一步,您可以为函数参数添加选择器函数:
function drag(selector) {
$(selector) ... your code
}
The next step is to create a jQuery plugin to encapsulate this behavior. 下一步是创建一个jQuery插件来封装此行为。 I've written many of these if you need advice.
如果您需要建议,我已经写了很多。
Using jQuery UI is not the best way to learn, imo. 使用jQuery UI并不是学习的最佳方法。
I modified your code a bit : 我对您的代码做了一些修改:
$(function(){
var currentDrag;
$('.draggable').click(function(){
currentDrag = $(this);
$(document).bind('mousemove.drag', function(e){
currentDrag.css({
left: e.pageX + 1,
top: e.pageY + 1
});
});
});
$('.box').click(function(){
if(currentDrag){
$(document).unbind('mousemove.drag');
currentDrag.css({
left: $('.box').position().left,
top: $('.box').position().top
});
currentDrag = "";
alert('Well Done! ^^')
}
});
});
<div class="draggable">
<!-- Image -->
</div>
<div class="box">
<!-- Placeholder -->
</div>
i have the answer! 我有答案! check this fiddle:
检查这个小提琴:
http://jsfiddle.net/5zVB8/8/ http://jsfiddle.net/5zVB8/8/
the draggables use classes and the script knows which draggable is which! 可拖动对象使用类,脚本知道哪个是可拖动对象!
the only problem is that if you click-drop a second item after click-dropping the first. 唯一的问题是,如果在单击第一项后单击第二项,则单击第二项。 an onclick handler for drop is on the drop "box" which is covered by the first draggable.
用于放置的onclick处理程序位于放置在第一个可拖动对象覆盖的“框”上。
you didn't mention anything about hiding the first box after dragging to the box. 您没有提到拖动到框后隐藏第一个框的任何信息。
EDIT: added a release function so you can click-drag out the dropped draggable that's in the box to anywhere in the screen. 编辑:添加了释放功能,因此您可以单击并拖动框中的拖放可拖动对象到屏幕上的任何位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.