2016-09-28 74 views
0

我试图在我的网站的旋转木马上播放一些内容,以便它根据按下的按钮向左或向右移动。这是我的示例代码:jQuery动画只有左右一次发生一次

HTML

<div class="red-bg"> 
    <div class="blue-bg" id="toAnimate"> 
    <p>Some text</p> 
    <p>Some other text</p> 
    <button id="leftButton">left</button> 
    <button id="rightButton">right</button> 
    </div> 
</div> 

CSS

.red-bg { 
    background: red; 
    height: 250px; 
    margin-left: 300px; 
    padding: 20px; 
    width: 250px; 
} 

.blue-bg { 
    background: blue; 
    position: relative; 
} 

JS

$(document).ready(function() { 

    function animateLeft() { 
    $("#toAnimate").animate({ 
     opacity: 0, 
     right: 100 
    }, 500, function() { 
     $('#toAnimate').css('right', '0'); 
     $('#toAnimate').css('opacity', '1'); 
    }); 
    } 

    function animateRight() { 
    $("#toAnimate").animate({ 
     opacity: 0, 
     left: 100 
    }, 500, function() { 
     $('#toAnimate').css('left', '0'); 
     $('#toAnimate').css('opacity', '1'); 
    }); 
    } 

    $('#leftButton').click(function() { 
    animateLeft(); 
    }); 

    $('#rightButton').click(function() { 
    animateRight(); 
    }); 

}); 

这里是链接我CodePen:http://codepen.io/leofontes/pen/NRgOxb

基本上,我的情况是,如果我按按钮第一,它的工作原理和动画播放至左侧,但是如果我按,则停止工作,只有衰出去但不走(左侧仍然有效)。

任何想法为什么这种行为正在发生或我可以如何解决它?谢谢! 如果需要更多的信息,请让我知道

+0

你只是改变代码'toAnimateLeft'在'$( '#toAnimate')的CSS( '左', '0');'和'左:-100 ' –

+0

为这两种方法添加这一行'$(“#toAnimate”)。attr('style','');' –

回答

1

问题: 在你的代码试图从右到左100像素,从左到右

首先,您删除左侧的风格在你的元素或做这样的

HTML

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width"> 
    <title>JS Bin</title> 
<script src="https://code.jquery.com/jquery-2.0.3.js"></script> 

</head> 
<body> 
    <div class="red-bg"> 
     <div class="blue-bg" id="toAnimate"> 
     <p>Some text</p> 
     <p>Some other text</p> 
     <button id="leftButton">left</button> 
     <button id="rightButton">right</button> 
     </div> 
    </div> 
</body> 
</html> 

JAVA SCRIPT

$(document).ready(function() { 

    function animateLeft() { 
    $("#toAnimate").animate({ 
     opacity: 0, 
     left: -100 
    }, 500, function() { 
     $('#toAnimate').css('left', '0'); 
     $('#toAnimate').css('opacity', '1'); 
    }); 
    } 

    function animateRight() { 
    $("#toAnimate").animate({ 
     opacity: 0, 
     left: 100 
    }, 500, function() { 
     $('#toAnimate').css('left', '0'); 
     $('#toAnimate').css('opacity', '1'); 
    }); 
    } 

    $('#leftButton').click(function() { 
    animateLeft(); 
    }); 

    $('#rightButton').click(function() { 
    animateRight(); 
    }); 


}); 
+0

非常明显,谢谢 – leofontes

+0

为'$(“#toAnimate”)添加此行。attr '风格','');'这两种方法..因为造型问题..这是你的确切解决方案@ leofontes –