JavaScript:单击时旋转 img

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19799846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:50:34  来源:igfitidea点击:

JavaScript: Rotate img on click

javascriptonclickrotation

提问by user2390516

I'm trying to make the img with the id image rotate using the onclick event handler to use the code in my function which grabs the image by ID assigns a variable name, then uses the variable name to rotate. I'm not really sure where i when wrong in my code.

我正在尝试使用 onclick 事件处理程序旋转带有 id 图像的 img 以使用我的函数中的代码,该代码通过 ID 抓取图像分配一个变量名称,然后使用变量名称进行旋转。当我的代码出错时,我不确定我在哪里。

   <section id="middle">
    <img id="image" src="images/flower.png" >   
    <button onclick="myFunction()">Click me</button>
    </section>

MyFunction(){
var img = document.getElementById("image");
img.rotate(20*Math.PI/180);
}

回答by Renato Zannon

You can do the rotation itself using CSS:

您可以使用 CSS 自行完成旋转:

.rotated-image {
  -webkit-transform: rotate(20deg);
          transform: rotate(20deg);
}

On the html:

在 html 上:

<section id="middle">
    <img id="image" src="images/flower.png" >   
    <button onclick="myFunction()">Click me</button>
</section>

And then, on the javascript, just add the class:

然后,在 javascript 上,只需添加类:

function myFunction() {
  var img = document.getElementById("image");
  img.setAttribute("class", "rotated-image");
}

Check out the result: http://jsbin.com/ibEmUFI/2/edit

查看结果:http: //jsbin.com/ibEmUFI/2/edit

回答by SCV

try to use div with id as a selector:

尝试使用带有 id 的 div 作为选择器:

<div id='image'><img src="images/flower.png" /></div>

 and 

var img = document.getElementById("image").getElementsByTagName('img');

worth a try!

值得一试!