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);
}
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);
}
Share
Improve this question
asked Nov 5, 2013 at 21:56
user2390516user2390516
171 gold badge1 silver badge6 bronze badges
3
-
1
For one thing, you have
onclick="myFunction()"
andMyFunction(){
. Case matters. You probably just wantonclick=MyFunction
. – Scott Mermelstein Commented Nov 5, 2013 at 22:00 - Thank you so much. Not sure how i missed that! – user2390516 Commented Nov 5, 2013 at 22:01
- 1 One of the errors was not having the key word function in front of the MyFunction. – user2390516 Commented Nov 5, 2013 at 22:17
3 Answers
Reset to default 1You 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./ibEmUFI/2/edit
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!
We can use rotate
to, well, rotate.
The
rotate
CSS property allows you to specify rotation transforms individually and independently of the transform property. This maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform property.
MDN
const rotate = () => {
document.querySelector("p").classList.add("rotate160deg");
}
.rotate160deg {
rotate: 160deg;
}
// demo related stuff:
div {
width: 150px;
margin: 0 auto;
}
p {
padding: 10px 5px;
border: 3px solid black;
width: 150px;
font-size: 1.2rem;
text-align: center;
}
.rotate {
transition: rotate 1s;
}
You can do the rotation itself using CSS:
<button onclick="rotate()">rotate</button>
<div>
<p class="rotate">
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742300174a4417885.html
评论列表(0条)