javascript - HTML5 拖放——在 HTML 表单上放置一个计数器来计算拖放次数

标签 javascript css html

我在网页左侧有 8 个列表项,在页面右侧有一个垃圾箱项。当我将每个元素拖入垃圾箱时,垃圾箱会吃掉该元素。我已经有了代码。现在我需要的是在我的网页上放置一个计数器来计算拖入垃圾箱的次数。请帮忙!下面是我完整的 HTML 和 javscript 代码。

<!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 = /*@cc_on!@*/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>

下面是我的 javascript 文件 h5utils.js: //JavaScript 文档

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);
  }
});



})();

最佳答案

您需要将您的代码添加到:

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

//your code

}

和放置事件

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

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

错误是因为您尝试在加载元素(div、链接等)之前将事件分配给链接列表。

window.onload 的作用是等待所有 HTML 准备就绪,然后分配事件。

var countDrops = 0;

window.onload = function(){
 var eat = ['yum!', 'gulp', 'burp!', 'nom'];
var yum = document.createElement('p');
  var msie = /*@cc_on!@*/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;
  });


  }

关于javascript - HTML5 拖放——在 HTML 表单上放置一个计数器来计算拖放次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19945268/

相关文章:

javascript - 我可以使用 CSS 或其他技术设计 Google 桌面小部件的样式吗?

html - 排列立方体面的 z-index

html - 如何重置特定超链接上的 CSS?

javascript - 如何使用函数参数从对象中选择数据?

javascript - CSS 位置固定导致内容重叠

javascript - jQuery 错误 - $(el).css ('float' ) 绝对或固定时 - 不同的浏览器返回不同的结果

css - 自动增长的无表布局问题

javascript - 如何通过 underscoreJS 遍历字母表

javascript - 从 react 组件传递数据

javascript - Angular 拖放列表 : Inputs with draggable property causing unintended behavior in IE