我是 Stack Overflow 和 javascript 的新手。我被要求创建一个应用程序,以便人们可以享受学习科学的乐趣。据我所知,我已经提出了问题,并且让它们可以拖动。不过,我一直无法让答案变得可删除。
我已经搜索了几天,寻找一些非常简单的 javascript 代码可以提供帮助,但是人们发布的所有内容对于初学者来说都太难了。
如果有人有任何简单的 javascript 代码可以帮助我的应用工作,或者任何有用的提示,那么将不胜感激。
我已经尝试上传我的代码,但它不允许我这样做。我已经设法将它上传到 JSFiddle,这是链接 -
jsfiddle.net/0t9h82vs/ - This just needs to be copied into your URL bar
谨致问候并感谢您的帮助!
我做了一个非常简单的版本,你可以这样做:
简单的 HTML:
<div class="drag">Drag Me!</div>
<div class="drop">Drop Here!</div>
首先,我们首先声明var
:
var activeE, clicking=false;
然后,为 .drag
添加 mousedown
事件:
$('.drag').mousedown(function(){
activeE=this;//This sets the active element to this
$(this).addClass('dragActive');//Adds the CSS class used
clicking=true;//Sets the clicking variable to true
$('body').addClass('noselect');//Not necessary, it just stops you from selecting text while dragging
});
接下来,您设置文档 mouseup
函数,以在元素被放下时重置所有变量:
$(document).mouseup(function(){
clicking=false;//Not that much explaining needed, it just resets everything
$('.dragActive').removeClass('dragActive');
activeE=null;
$('body').removeClass('noselect');
});
然后,我们添加一点代码让用户可以看到元素被拖动:
$(document).mousemove(function(e){
if(clicking==true){
var x = e.clientX,y = e.clientY;//jQuery methods, finds the cursors position.
$('.drag').css({top:(y-($('.drag').height()/2)), left:(x-($('.drag').width()/2))});//And this changes the `activeE`'s position in mouse move.
}
});
然后是 drop 函数。非常简单,它只是将 activeE
附加到 .drop
中:
$('.drop').mouseup(function(){
clicking=false;//again, resets.
$(this).append(activeE);//and appends
$('.dragActive').removeClass('dragActive');
$('body').removeClass('noselect');
});
然后,一点 CSS 来完成它:
.dragActive{
pointer-events:none;
position:absolute;
}
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor:move;
}
还有田田!全部完成!
完整的 JS:
$(function(){
var activeE, clicking=false;
$('.drag').mousedown(function(){
activeE=this;
$(this).addClass('dragActive');
clicking=true;
$('body').addClass('noselect');
});
$(document).mouseup(function(){
clicking=false;
$('.dragActive').removeClass('dragActive');
activeE=null;
$('body').removeClass('noselect');
});
$(document).mousemove(function(e){
if(clicking==true){
var x = e.clientX,
y = e.clientY;
$('.drag').css({top:(y-($('.drag').height()/2)), left:(x-($('.drag').width()/2))});
}
});
$('.drop').mouseup(function(){
clicking=false;
$(this).append(activeE);
$('.dragActive').removeClass('dragActive');
$('body').removeClass('noselect');
});
});
和CSS:
.drag{
background:pink;
padding:5px;
border-radius:5px;
width:100px;
cursor:move;
}
.dragActive{
pointer-events:none;
position:absolute;
}
.drop{
width:500px;
height:500px;
border:1px solid red;
}
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor:move;
}