简体   繁体   中英

Animate div back to its original position (cycle needs to be repeated)

I've the following HTML

<div id="mrdiv"/>
<input type="button" style="position: absolute;top: 100px;"onclick="one();"></input>
<input type="button" style="position: absolute;top: 100px; left: 50px;" onclick="two();"/>

JAVASCRIPT

function one(){
$("#mrdiv").stop(true).animate({right: "+=214"},200);
}

function two(){
$("#mrdiv").stop(true).animate({left: "+=214"},200);
}

CSS

#mrdiv{
    position:absolute;
    background-color: black;
    width: 100px;
    height: 100px;
}

Last but not least: http://jsfiddle.net/25pYY/3/ For some odd reason, I can't understand why the buttons don't work but I guess the code is enough to understand what I want.

Basically, when I execute the animate functions the div animate properly but only in the first passage to the code. With this I mean that If I click the button one then two won't work, or vice-versa. I need them both to work and to do this repeatdly but I don't understand why they wont. Any ideas on this one? Sorry for the broken fiddle, I'll try and get it to work while waiting!

Your right and left values are competing with each other. You need to disable them as appropriate:

http://jsfiddle.net/isherwood/25pYY/9

function one() {
    $("#mrdiv").stop(true).animate({
        right: "+=14"
    }, 200).css('left', 'auto');
}

function two() {
    $("#mrdiv").stop(true).animate({
        left: "+=14"
    }, 200).css('right', 'auto');
}

It would be a good move to get your click handlers out of your HTML, like so:

http://jsfiddle.net/isherwood/25pYY/10

$(function () {
    $('#mrdiv input').click(function () {
        if ($(this).index() == 1) {
            one();
        } else {
            two();
        }
    });
});

As I suspected, you actually wanted different behavior than what your code would indicate. Here's how you might keep the animations from jumping to the sides of the screen. Only animate one property:

http://jsfiddle.net/isherwood/25pYY/12

function one() {
    $("#mrdiv").stop(true).animate({
        left: "-=14"
    }, 200);
}

function two() {
    $("#mrdiv").stop(true).animate({
        left: "+=14"
    }, 200);
}

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