简体   繁体   中英

Javascript onclick only works once

So I made this,

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

Found at: https://jsfiddle.net/dkjufqn0/

And in it, a coin spins. However, it only fires once. The first time I click it. It doesn't fire again after. Help!

Every time you click the coin it remains at the 1800 degrees, to rotate it on each click you need to increment its degrees as in below example:

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> 

Are you sure about that? place a console.log(in that handler to check it)

I think your code is fine, except the rotateY calls seem to do nothing after the first click because you always set it to the same value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM