[英]How to use in jQuery :not and hasClass() to get a specific element without a class
[英]How to make this jQuery function more generic (use class without losing specific positioning)
如何使这个jQuery函数更通用? 我希望#draggable是.draggable,并且函数可以确定单击了.draggable,然后处理该元素,直到解除绑定为止。
谢谢!
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>
第一步,您可以为函数参数添加选择器函数:
function drag(selector) {
$(selector) ... your code
}
下一步是创建一个jQuery插件来封装此行为。 如果您需要建议,我已经写了很多。
使用jQuery UI并不是学习的最佳方法。
我对您的代码做了一些修改:
$(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>
我有答案! 检查这个小提琴:
可拖动对象使用类,脚本知道哪个是可拖动对象!
唯一的问题是,如果在单击第一项后单击第二项,则单击第二项。 用于放置的onclick处理程序位于放置在第一个可拖动对象覆盖的“框”上。
您没有提到拖动到框后隐藏第一个框的任何信息。
编辑:添加了释放功能,因此您可以单击并拖动框中的拖放可拖动对象到屏幕上的任何位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.