当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - HTML5 drag and drop --place a counter on HTML form that will count number of drags

问题描述:

I have 8 list items on a web page floated towards the left of the page and a dustbin item towards the right of the page. When I drag each of the item into the dustbin, the dustbin eats away the item. I already have the code for that. Now what I need is to place a counter on my web page that will count the number of drags into the dustbin. Please help! Below is my complete HTML and javscript code.

<!DOCTYPE html>

<html>

<head>

<meta content="text/html; charset=UTF-8" http-equiv="content-type"/>

<title>HTML5 Drag and drop demonstration</title>

<style type="text/css">

* {

margin: 0;

padding: 0;

}

body {

margin: 50px;

font-family: helvetica, arial;

}

li {

list-style: none;

/* padding: 10px;*/

}

li a {

text-decoration: none;

color: #000;

margin: 10px;

width: 150px;

/*border: 3px dashed #999;*/

border: 5px solid #000;

/* background: #eee;*/

background:#FFF;

padding: 10px;

cursor: pointer;

-moz-user-select:none;

/* -webkit-user-drag: element;*/

-khtml-user-drag: element;

display: block;;

}

*:-khtml-drag {

background-color: rgba(238,238,238, 0.5);

}

a:hover:after {

/* content: ' (drag me)';*/

content: ' (throw me!)';

}

li.over {

border-color: #333;

background: #ccc;

}

#bin {

background: url(images/dustbinnew1.jpg) top right no-repeat;

height: 250px;

width: 166px;

float:right;

border: 5px solid #000;

position: relative;

}

#bin.over {

background: url(images/dustbinnew2.jpg) repeat;

}

#bin p {

font-weight: bold;

text-align: center;

position: absolute;

bottom: 20px;

width: 166px;

font-size: 32px;

color: #fff;

text-shadow: #000 2px 2px 2px;

}

</style>

</head>

<body>

<div id="bin"></div>

<ul>

<li><a id="one" href="#">one</a></li>

<li><a href="#" id="two">two</a></li>

<li><a href="#" id="three">three</a></li>

<li><a href="#" id="four">four</a></li>

<li><a href="#" id="five">five</a></li>

<li><a href="#" id="six">six</a></li>

<li><a href="#" id="seven">seven</a></li>

<li><a href="#" id="eight">eight</a></li>

</ul>

<script src="h5utils.js"></script>

<script>

var eat = ['yum!', 'gulp', 'burp!', 'nom'];

var yum = document.createElement('p');

var msie = /*@[email protected]*/0;

yum.style.opacity = 1;

var links = document.querySelectorAll('li > a'), el = null;

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

el = links[i];

// even required? Spec says yes, browsers say no.

el.setAttribute('draggable', 'true');

addEvent(el, 'dragstart', function (e) {

e.dataTransfer.setData('Text', this.id); // set *something* required otherwise doesn't work

});

}

var bin = document.querySelector('#bin');

addEvent(bin, 'dragover', function (e) {

if (e.preventDefault) e.preventDefault(); // allows us to drop

this.className = 'over';

return false;

});

addEvent(bin, 'dragleave', function () {

this.className = '';

});

addEvent(bin, 'drop', function (e) {

if (e.stopPropagation) e.stopPropagation(); // stops the browser from redirecting...why???

var el = document.getElementById(e.dataTransfer.getData('Text'));

el.parentNode.removeChild(el);

// stupid nom text + fade effect

bin.className = '';

yum.innerHTML = eat[parseInt(Math.random() * eat.length)];

var y = yum.cloneNode(true);

bin.appendChild(y);

setTimeout(function () {

var t = setInterval(function () {

if (y.style.opacity <= 0) {

if (msie) { // don't bother with the animation

y.style.display = 'none';

}

clearInterval(t);

} else {

y.style.opacity -= 0.1;

}

}, 50);

}, 250);

return false;

});

</script>

</body>

</html>

Below is my javascript file h5utils.js:

// JavaScript Document

var addEvent = (function () {

if (document.addEventListener) {

return function (el, type, fn) {

if (el && el.nodeName || el === window) {

el.addEventListener(type, fn, false);

} else if (el && el.length) {

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

addEvent(el[i], type, fn);

}

}

};

} else {

return function (el, type, fn) {

if (el && el.nodeName || el === window) {

el.attachEvent('on' + type, function () { return fn.call(el, window.event); });

} else if (el && el.length) {

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

addEvent(el[i], type, fn);

}

}

};

}

})();

(function () {

var pre = document.createElement('pre');

pre.id = "view-source"

// private scope to avoid conflicts with demos

addEvent(window, 'click', function (event) {

if (event.target.hash == '#view-source') {

// event.preventDefault();

if (!document.getElementById('view-source')) {

// pre.innerHTML = ('<!DOCTYPE html>\n<html>\n' + document.documentElement.innerHTML + '\n</html>').replace(/[<>]/g, function (m) { return {'<':'&lt;','>':'&gt;'}[m]});

var xhr = new XMLHttpRequest();

// original source - rather than rendered source

xhr.onreadystatechange = function () {

if (this.readyState == 4 && this.status == 200) {

pre.innerHTML = this.responseText.replace(/[<>]/g, function (m) { return {'<':'&lt;','>':'&gt;'}[m]});

prettyPrint();

}

};

document.body.appendChild(pre);

// really need to be sync? - I like to think so

xhr.open("GET", window.location, true);

xhr.send();

}

document.body.className = 'view-source';

var sourceTimer = setInterval(function () {

if (window.location.hash != '#view-source') {

clearInterval(sourceTimer);

document.body.className = '';

}

}, 200);

}

});

})();

网友答案:

you need add your code to:

var countDrops = 0;
window.onload = function(){

//your code

}

and on drop event

  addEvent(bin, 'drop', function (e) {
    if (e.stopPropagation) e.stopPropagation(); // stops the browser from redirecting...why???

    /* CONTADOR */
    countDrops++;
    alert(countDrops);

the error was because you tried assigning events to the list of links before the elements (divs, links, etc.) were loaded.

with window.onload does is wait for all the HTML is ready and then assigns the events.

var countDrops = 0;

window.onload = function(){
 var eat = ['yum!', 'gulp', 'burp!', 'nom'];
var yum = document.createElement('p');
  var msie = /*@[email protected]*/0;
 yum.style.opacity = 1;

  var links = document.querySelectorAll('li > a'), el = null;
  for (var i = 0; i < links.length; i++) {
    el = links[i];

    // even required? Spec says yes, browsers say no.
    el.setAttribute('draggable', 'true');

    addEvent(el, 'dragstart', function (e) {
      e.dataTransfer.setData('Text', this.id); // set *something* required otherwise doesn't work
    });
  }

  var bin = document.querySelector('#bin');

  addEvent(bin, 'dragover', function (e) {
    if (e.preventDefault) e.preventDefault(); // allows us to drop
    this.className = 'over';
    return false;
  });

  addEvent(bin, 'dragleave', function () {
    this.className = '';
  });

  addEvent(bin, 'drop', function (e) {
    if (e.stopPropagation) e.stopPropagation(); // stops the browser from redirecting...why???

    /* CONTADOR */
    countDrops++;
    alert(countDrops);


    var el = document.getElementById(e.dataTransfer.getData('Text'));

    el.parentNode.removeChild(el);

    // stupid nom text + fade effect
    bin.className = '';
    yum.innerHTML = eat[parseInt(Math.random() * eat.length)];

    var y = yum.cloneNode(true);
    bin.appendChild(y);

    setTimeout(function () {
      var t = setInterval(function () {
        if (y.style.opacity <= 0) {
          if (msie) { // don't bother with the animation
            y.style.display = 'none';
          }
          clearInterval(t);
        } else {
          y.style.opacity -= 0.1;
        }
      }, 50);
    }, 250);

    return false;
  });


  }
分享给朋友:
您可能感兴趣的文章:
随机阅读: