简体   繁体   中英

JAvascript 180 to -180 rotate

Right now when the user clicks on this image, it rotates 180 degrees.
I want to update it to do this: If the user clicks the image, it rotates 180 degrees, but if the user clicks the image again, it rotates back to its original position.

Here's my javascript:

var value = 0
$("#row-1").click(function(){
    value +=180;
    $("#image1").rotate({ animateTo:value});
});

HTML:

<th style="text-align:left;" width="20%" id="row-2">
    Company<br>
    <span class="move_right">Name</span> 
    <img src="/images/sort-arrow-up.png" title="Sort by Company Name" alt="Sort by Company Name" class="sort-right move-left" id="image2" />
</th>

Maintain a separate variable for how much to change the angle and negate it on each click:

var value = 0;
var delta = 180;
$("#row-1").click(function(){
    value += delta;
    delta = -delta;
    $("#image1").rotate({ animateTo:value});
});

I would suggest to set your value = -180 at the begening and then every time the user click you do a

value = value * -1;

This will give : 180, -180, 180, -180 (...) and so on. It's what you want ?

var angle = 180;
$("#row-1").toggle(function(){
    value +=angle ;
    $("#image1").rotate({ animateTo:value});
    angle = angle*(-1);
});

I know this has already been answered, but I wanted to get an answer with a fiddle on here. There is also a dependency on the jQueryRotate plugin .

Working Demo in Fiddle

HTML :

<table>
    <th id="row-1">
        <p>Company</p>
        <span>Name</span> 
        <img id="image1" src="http://i.imgur.com/wO5gsMy.png"
             title="Sort by Company Name" alt="Sort by Company Name"
             width="25" height="25"/>
    </th>
</table>

JavaScript :

var value = 0;
$("#row-1").click(function(){
    value = value ? 0: 180
    $("#image1").rotate({ animateTo:value});
});

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