Html5:" ondrop"当我放下一个项目时,事件不会触发

时间:2017-09-20 12:49:39

标签: javascript jquery html html5 drag-and-drop

在我的应用程序中,我有以下带有js和样式表的html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Drag'n'Drop demo</title>

        <style>
            #dropArea{
                min-width:50%;
                min-height:800px;
                background-color:#FF00BB;
                float: left;
            }

            #imgArea {
                min-width:49%;
                min-height:800px;
                background-color:#0F0FBB;
                float: right;
            }

            #imgArea img {
                display:block;
                margin:5px;
            }

        </style>
         <script src="https://code.jquery.com/jquery-3.2.1.min.js"
         integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
         crossorigin="anonymous"></script>
        <script>
          var onDropCallback=function(event){
            event.preventDefault();
            console.log("Droped")
          }

          var dragSrart=function(event){
            // alert("DragStarted")
            console.log("Drag Started");
          }

          var ondragoverCallback=function(event){
            var elem=event.target || event.srcElement;
            $(elem).css('border',"1px solid black");
          }

          var dragEndCallback=function(event){
            event.preventDefault();
            console.log("Drag End HAppened");
            $("#dropArea").css('border',"none");
          }

        </script>
    </head>
    <body>
        <div id="dropArea" ondragover="ondragoverCallback(event)" ondrop="onDropCallback(event)" ></div>
        <div id="imgArea">
            <img draggable="true" ondragstart="dragSrart(event)" ondragend="dragEndCallback(event)" src="https://kazasou.files.wordpress.com/2010/08/g288.gif">
        </div>
    </body>
</html>

但由于某些原因即使事件ondragstartondragend被解雇,我也无法弄清楚为什么drop事件根本不会触发。我查看了https://www.w3schools.com/HTML/html5_draganddrop.asphttps://www.w3schools.com/HTML/tryit.asp?filename=tryhtml5_draganddrop,但我无法弄清楚示例中的代码有多么不同。

1 个答案:

答案 0 :(得分:0)

正如您所见:https://www.w3schools.com/HTML/tryit.asp?filename=tryhtml5_draganddrop,您必须在preventDefault事件期间dragover,因此ondragoverCallback应具有以下代码:

var ondragoverCallback=function(event){
   event.preventDefault();
   var elem=event.target || event.srcElement;
   $(elem).css('border',"1px solid black");
}