简体   繁体   中英

onClick event fails to perform function

I have an image within my program that I want the user to be able to rotate 90 degrees with each click. Because the image is automatically placed in my program at a tilted angle, I needed to use CSS to rotate the image before allowing the user to do so. This way, as it is clicked, the image will appear horizontally and sideways. Currently, the onClick event in my HTML code appears to only be working once.

I have attempted declaring a variable to increase the rotational value at each click but doing this removed the rotation altogether

<html>
   <head>
   <script>
     var degrees = 57;
     function rotateImage() {
       var img = document.getElementById('c-channel');
       degrees += 90;
       img.style.transform = 'rotate(degrees)';  
 }
 </script>

 <style>
    #c-channel{
      position: absolute;
      cursor:move;
      width:190px;
      height:150px;
      transform:rotate(57deg);
   }
   </style>
   </head>

 <body>
   <img id="c-channel" src="https://cdn.glitch.com/2a39b17c-6b95-46ec9d5c-cf9db18cd879%2Foutput-onlinepngtools%20(6).png?v=1564485433523" onclick="rotateImage()"> 
 </body>
</html>

I expected the program to allow the user to rotate the image another 90 degrees with every click but instead, clicking the image provides no visible change.

You aren't using the degrees variable, you can use string template as follows:

 var degrees = 57; function rotateImage() { var img = document.getElementById('c-channel'); degrees = (degrees % 360) + 90; //img.style.transform = 'rotate(' + degrees + 'deg)'; img.style.transform = `rotate(${degrees}deg)`; } 
 #c-channel { position: absolute; cursor: move; width: 190px; height: 150px; transform: rotate(57deg); border: grey; } 
 <img id="c-channel" onclick="rotateImage()"> 

You are using degrees as a string rather than the actual value, and you also need to append a unit next to it.

 var degrees = 57; var img = document.getElementById('c-channel'); function rotateImage() { degrees += 90; img.style.transform = 'rotate('+degrees+'deg)'; } 
 #c-channel { position: absolute; cursor: move; width: 190px; height: 150px; transform: rotate(57deg); } 
 <img id="c-channel" src="https://cdn.glitch.com/2a39b17c-6b95-46ec9d5c-cf9db18cd879%2Foutput-onlinepngtools%20(6).png?v=1564485433523" onclick="rotateImage()"> 

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