How to fix drag and drop JavaScript

旧巷老猫 提交于 2021-02-08 05:10:44

问题


I created this page and script to drag and drop an object using JavaScript, HTML, CSS. I spotlight object follow mouse to hover over the page item and drop it on the container but my problem is the drag and drop is not working?

Here's the code:

HTML:

<body onload="initPage()">

    <div class="container">
        <span id="spotLight"></span>
        <h1>Drag and Drop Demos</h1>

        <h2>Page Elements</h2>
        <p>
            Drag the elements on the right into the drop area.
        </p>
        <div id="dd-elements" class="clearfix">
            <ul id="drag-elements">
                <li draggable="true">Element One</li>
                <li draggable="true">Element Two</li>
                <li draggable="true">Element Three</li>
                <li draggable="true">Element Four</li>
                <li draggable="true">Element Five</li>
            </ul>

            <div id="drop-target-one">
                Drop Here!
            </div>
        </div>
    </div>
</body>

CSS:

.container {
    max-width: 960px;
    margin: 0 auto;
    padding: 1em;
}



#drop-target-one,
#dd-files,
#dd-images {
    border: 5px dashed #D9D9D9;
    border-radius: 10px;
    padding: 5em 2em;
    text-align: center;
}

.over {
    background: #F7F7F7;
}

#drag-elements {
    list-style: none;
    padding: 0;
    margin: 0 0 1em;
}

#drag-elements li {
    display: inline-block;
    padding: 0.5em 1em;
    margin: 0 1em 1em 0;
    border: 1px solid #D9D9D9;
    background: #F7F7F7;
    border-radius: 3px;
}

//spotLight
#spotLight {
 position: absolute;
  left: 50px;
  top: 50px;
  width: 200px;
  height: 200px;
  border-radius: 20px;

  box-shadow: 0px 0px 0px 300px rgba(255, 255, 255, 0.5);
}

#spotLight:after {
  content: '';
  position: absolute;
  left: -25px;
  top: -25px;
  right: -25px;
  bottom: -25px;
  border: solid 1px gray;
  border-radius: 25px;

  box-shadow: 0px 0px 0px 300px rgba(255, 255, 255, 0.6);
}


.clearfix {
  *zoom: 1; }

.clearfix:before,
.clearfix:after {
  display: table;
  line-height: 0;
  content: ""; }

.clearfix:after {
  clear: both; }

JavaScript:

window.onload = function() {


    var dropZoneOne = document.querySelector('#drop-target-one');
    var dragElements = document.querySelectorAll('#drag-elements li');
    var elementDragged = null;

    for (var i = 0; i < dragElements.length; i++) {


        dragElements[i].addEventListener('dragstart', function(e) {
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text', this.innerHTML);
            elementDragged = this;
        });


        dragElements[i].addEventListener('dragend', function(e) {
            elementDragged = null;
        });
    };


    dropZoneOne.addEventListener('dragover', function(e) {
        if (e.preventDefault) {
            e.preventDefault();
        }

        e.dataTransfer.dropEffect = 'move';

        return false;
    });


    dropZoneOne.addEventListener('dragenter', function(e) {
        this.className = "over";
    });

    // Event Listener for when the dragged element leaves the drop zone.
    dropZoneOne.addEventListener('dragleave', function(e) {
        this.className = "";
    });


    dropZoneOne.addEventListener('drop', function(e) {
        if (e.preventDefault) e.preventDefault(); 
    if (e.stopPropagation) e.stopPropagation(); 

        this.className = "";
        this.innerHTML = "Dropped " + e.dataTransfer.getData('text');

        document.querySelector('#drag-elements').removeChild(elementDragged);
        elementDragged = null;

        return false;
    });

};
function initPage() { 
    document.onmousemove = followMe;
}

function followMe(evt) {
    var evt = (evt) ? evt : ((window.event) ? event : null);
    var object = document.getElementById('spotLight');
        object.style.left = evt.clientX - (object.offsetWidth/2) + 'px';
        object.style.top = evt.clientY - (object.offsetHeight/2) + 'px';
        return;
}

Fiddle:

http://jsfiddle.net/Ca5r2/


回答1:


Ok, a couple of things I found to get the jsFiddle working.

First, the reason the elements aren't draggable has to do with your pseudo element #spotlight:after. It is positioned 'absolute' with top, left, bottom, and right values of -25px. I don't think is doing what you intended. An element with those positions is going to take up the entire screen because it will stretch from 25px to the left of the left border to 25px after the right edge and so on. A temporary solution is to add the css attribute

pointer-events: none;

Secondly, you have

<body onload="initPage()">

and

function initPage() { 

Normally this would be fine, but in JSFiddle the javascript window is scoped inside of the page onload handler and so the functions are scoped locally. To get them into the global scope you can do several things, but temporarily I changed the function to be explicitly added to the window scope:

window['initPage'] = function() { 

Also, because we are already scoped inside of the onload handler I removed the

window.onload = function() {

scoping, including the end braces.

Here is the working JSFiddle




回答2:


Why don't you use html5 ?

<head>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("Text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<img id="drag1" src="img_logo.gif" draggable="true"
ondragstart="drag(event)" width="336" height="69">

source : w3s




回答3:


I strongly recommend you looking in on using jQuery UI for this. Check out the draggable and droppable widgets.



来源:https://stackoverflow.com/questions/24985601/how-to-fix-drag-and-drop-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!