OnDrag JavaScript / JQUERY

时间:2018-01-18 15:49:07

标签: javascript jquery

我正在尝试删除并拖动我正在学习本教程:https://youtu.be/hqSlVvKvvjQ?t=503

但是我的事件没有被解雇。有什么问题?

var dropzone = $('#dropzone');

dropzone.ondragover = function() {
  console.log("entered");
  this.className = 'dropzone dragover';
  return false;
};
dropzone.ondragleave = function() {
  this.className = 'dropzone';
  return false;
};
dropzone.ondrop = function(e) {
  e.preventDefault();
  this.className = 'dropzone';
  return false;
};
.dropzone {
    border: 2px dashed #ccc;
    width: 100%;
    height: 100%;
    color: #ccc;
    text-align: center;
    padding: 60px;
}
.dropzone p {
    font-size: 25px;
}
.dropzone.dragover {
    border-color: #000;
    color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropzone" id="dropzone">
  <p>Drag & Drop</p>
</div>

1 个答案:

答案 0 :(得分:0)

变量dropzone是一个jQuery对象,因为你传入了$('#dropzone')。因此,您需要使用jQuery样式事件来实现此功能。

&#13;
&#13;
var dropzone = $('#dropzone');

dropzone.on('dragover', function() {
    $(this).addClass('dragover');
    return false;
});

dropzone.on('dragleave', function() {
    $(this).removeClass('dragover');
    return false;
});

dropzone.on('drop', function(e) {
    e.preventDefault();
    $(this).removeClass('dragover');
    return false;
});
&#13;
.dropzone {
    border: 2px dashed #ccc;
    width: 100%;
    height: 100%;
    color: #ccc;
    text-align: center;
    padding: 60px;
}
.dropzone p {
    font-size: 25px;
}
.dropzone.dragover {
    border-color: #000;
    color: #000;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropzone" id="dropzone">
  <p>Drag & Drop</p>
</div>
&#13;
&#13;
&#13;

或者其他方式,只需使用香草js。为此,将DOM元素传递给dropzone变量并保留其他类似内容的文章。

&#13;
&#13;
var dropzone = document.getElementById('dropzone');

dropzone.ondragover = function() {
    this.className = 'dropzone dragover';
    return false;
};

dropzone.ondragleave = function() {
    this.className = 'dropzone';
    return false;
};

dropzone.ondrop = function(e) {
    e.preventDefault();
    this.className = 'dropzone';
    return false;
};
&#13;
.dropzone {
    border: 2px dashed #ccc;
    width: 100%;
    height: 100%;
    color: #ccc;
    text-align: center;
    padding: 60px;
}
.dropzone p {
    font-size: 25px;
}
.dropzone.dragover {
    border-color: #000;
    color: #000;
}
&#13;
<div class="dropzone" id="dropzone">
  <p>Drag & Drop</p>
</div>
&#13;
&#13;
&#13;