我已经问过这个问题,但它并没有解决我的问题(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/