JavaScript/CSS : How to start animation from cursor position

标签 javascript css

我已经问过这个问题,但它并没有解决我的问题(JavaScript / CSS - How can I start an animation, creating new Divs from cursor position?)。

我找到了一个解决方案,但它似乎无法在 Mozilla 和 Opera 上正常工作。此外,当我多次单击时,div 开始闪烁,这不是我想要的。我需要同时拥有多个 div,以便同时拥有多个动画。这是现有游戏的示例:http://www.cram.com/flashcards/games/stellar-speller/gre-hit-parade-group-1-320949请不要使用 jQuery,只使用普通的 Javascript。谢谢!

<!DOCTYPE html>
    <html>
   <head>
   <style>
     #table{
   height:300px;
   width:900px;
  background:red;

     }
 #ball {
     width: 25px;
     height: 25px;
     position: absolute;
       background-color: white;
     border-radius:50px;
    display:none;
    z-index:11;


   }
   </style>
   <script>  function animation(){ var elem = 
    document.getElementById("ball"); 
   document.getElementById("ball").style.display ='block';
    document.getElementById("ball").disabled = true;
  var x = event.clientX;
   var y = event.clientY;
  var id = setInterval(frame, 2);
   function frame() {
    if (x == 900) {
    clearInterval(id);

   } 
  else {
  x++;   
  elem.style.top = y + 'px';
  elem.style.left = x + 'px'; 
   }
   }
     }
   </script>
  </head>
  <body>
   <div id="table" onclick="animation()">
    <div id="ball"></div>
   </body>
   </html>

最佳答案

您的代码中几乎没有问题。首先,每次单击时都必须克隆或创建一个新球(请注意 cloning 元素不会复制附加事件)。不要混合使用 HTML 和 Javascript 并使用 addEventListener,它可以让您将事件作为参数

document.getElementById('table').addEventListener("click",animation);

function animation(event){
    var ball = document.getElementById("ball");
    //clone element or create another one (you should set a class in you css)
    var elem = ball.cloneNode(true);
  document.getElementById("table").appendChild(elem);

    elem.style.display ='block';
//    document.getElementById("ball").disabled = true;
    var x = event.clientX;
    var y = event.clientY;
 
    var id = setInterval(frame, 2);
    
    function frame() {
        if (x == 900) {
            clearInterval(id);
        } 
        else
        {
            x++;
            elem.style.top = y + 'px';
            elem.style.left = x + 'px'; 
        }
    }
}
#table{
  height:300px;
  width:900px;
  background:red;
}

#ball {
  width: 25px;
  height: 25px;
  position: absolute;
  background-color: white;
  border-radius:50px;
  display:none;
  z-index:11;
}
<div id="table">
    <div id="ball"></div>
</div>

关于JavaScript/CSS : How to start animation from cursor position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49475714/

相关文章:

JavaScript 木马剖析

html - 如何将一个绝对元素置于另一个绝对元素的中心,可用于旋转和动画目的

jquery - 如何使用 jQuery 获取具有特定 CSS 属性的第一个父对象?

css - 单列覆盖多行

javascript - 在 ReactJS 中调用函数嵌套状态对象

javascript - 循环setInterval函数

css - 使用 Unicode 字体作为@font-face

css - 在所有 css 规则中应用 border-box

javascript - 如何在vue模板中定义变量?

javascript - jQuery/IE10-SCRIPT438 : Object doesn't support property or method 'data'