简体   繁体   English

将div动画化回其原始位置(需要重复循环)

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

I've the following HTML 我有以下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 JAVASCRIPT

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

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

CSS 的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. 最后但并非最不重要的一点: http : //jsfiddle.net/25pYY/3/由于某些奇怪的原因,我不明白为什么按钮不起作用,但是我想代码足以理解我想要的东西。

Basically, when I execute the animate functions the div animate properly but only in the first passage to the code. 基本上,当我执行动画功能时,div才能正确动画,但仅在代码的第一段中进行。 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. 你的rightleft值相互竞争。 You need to disable them as appropriate: 您需要适当地禁用它们:

http://jsfiddle.net/isherwood/25pYY/9 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: 将点击处理程序移出HTML会是一个不错的选择,例如:

http://jsfiddle.net/isherwood/25pYY/10 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 http://jsfiddle.net/isherwood/25pYY/12

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM