Javascript onclick只能运行一次

时间:2016-01-22 12:39:06

标签: javascript html css onclick

所以我做了这个,

var Coin = document.getElementById("coin");

Coin.onclick = function() {
    Coin.style.webkitTransform = "rotateY(1800deg)";
    Coin.style.MozTransform = "rotateY(1800deg)";
    Coin.style.msTransform = "rotateY(1800deg)";
    Coin.style.OTransform = "rotateY(1800deg)";
    Coin.style.transform = "rotateY(1800deg)";
}

发现于:https://jsfiddle.net/dkjufqn0/

在其中,一枚硬币旋转。但是,它只发射一次。我第一次点击它。它之后再没有发射。救命啊!

2 个答案:

答案 0 :(得分:8)

每次点击硬币时,它都保持在1800度,要在每次点击时旋转它,你需要增加它的度数,如下例所示:

https://jsfiddle.net/dkjufqn0/1/



var Coin = document.getElementById("coin");
var degrees = 0;
Coin.onclick = function() {
  degrees += 1800;
  console.log(degrees)
  Coin.style.webkitTransform = "rotateY(" + degrees + "deg)";
  Coin.style.MozTransform = "rotateY(" + degrees + "deg)";
  Coin.style.msTransform = "rotateY(" + degrees + "deg)";
  Coin.style.OTransform = "rotateY(" + degrees + "deg)";
  Coin.style.transform = "rotateY(" + degrees + "deg)";
}

body {
  -webkit-transform: perspective(500px);
  -webkit-transform-style: preserve-3d;
}

.coin {
  background-image: url("http://coins.thefuntimesguide.com/images/blogs/presidential-dollar-coin-reverse-statue-of-liberty-public-domain.png");
  background-size: 100% 100%;
  border-radius: 100%;
  height: 100px;
  margin: 50px auto;
  position: relative;
  width: 100px;
  -webkit-transition: 2s linear;
  -webkit-transform-style: preserve-3d;
}

<div class="coin" id="coin"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

你确定吗? 放置一个console.log(在该处理程序中进行检查)

我认为你的代码很好,除了在第一次点击后,rotateY调用似乎什么都不做,因为你总是把它设置为相同的值。