[removed] Rotate img on click

2019-02-28 15:14发布

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.

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

2条回答
Fickle 薄情
2楼-- · 2019-02-28 15:35

try to use div with id as a selector:

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

 and 

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

worth a try!

查看更多
冷血范
3楼-- · 2019-02-28 15:50

You can do the rotation itself using CSS:

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

On the 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:

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

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

查看更多
登录 后发表回答