简体   繁体   English

onClick事件无法执行功能

[英]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. 我的程序中有一张图像,希望用户每次单击都可以旋转90度。 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. 因为图像是自动倾斜放置在程序中的,所以在允许用户这样做之前,我需要使用CSS旋转图像。 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. 目前,我的HTML代码中的onClick事件似乎只能运行一次。

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. 我希望该程序允许用户每次单击将图像再旋转90度,但是单击图像不会产生可见变化。

You aren't using the degrees variable, you can use string template as follows: 您没有使用degrees变量,可以使用字符串模板,如下所示:

 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()"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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