尝试使用shake.js创建多个震动

时间:2012-11-27 22:03:52

标签: javascript android iphone javascript-events

所以我想在这里完成的是每次手机动摇时都会收到警报。但我一直收到一个错误,说Uncaught TypeError:无法调用未定义的方法'addEventListener',是不是因为它不知道'震动'是什么?不止一次摇晃的原因是因为根据动摇的不同添加不同的动画。

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8" />
 <meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no" />
 <meta name="apple-mobile-web-app-capable" content="yes" />
 <title>Shake animation</title>
 <style type="text/css">
 body {
background: #E9E9E9; 
color: #333; 
font: 1em/1.3em "Helvetica Neue", Helvetica, Arial, Verdana, sans-serif; /* 16px /    21px */
text-shadow: rgba(255,255,255,0.8) 0 1px 0;
text-align: center;
    }
    </style>
    <script type="text/javascript" src="shake.js"></script>
    </head>
    <body>
       <div class="answerListener" id="answer1"></div>
       <div class="answerListener" id="answer2"></div>
       <div class="answerListener" id="answer3"></div>
       <div class="answerListener" id="answer4"></div>

    <script type="text/javascript">
    window.onload = function() {


   var answer = document.getElementsByClassName('answerListener');
   var current = 1;

   for (i = 0; answer.length; i++) {
   answer[i].addEventListener('shake', function() {

   if (current == 1) {
      alert('shake1');
   }
   if (current == 2) {
      alert('shake2');
   }
   if (current == 3) {
      alert('shake3');
   }
   if (current == 4) {
      alert('shake4');
   }
   current = current + 1;
   }, false);
}   
};

</script>
 </body>

1 个答案:

答案 0 :(得分:1)

除了一个小问题之外,您的代码看起来很好:您的for循环不会终止:

for (i = 0; answer.length; i++) {

应该是

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

您收到错误是因为i超过answer.length后,answer[i]未定义,因此answer[i].addEventListener正在尝试调用不存在元素的方法。< / p> 祝你好运。