来自当前位置的jquery动画

时间:2015-02-21 17:02:34

标签: javascript jquery

我希望动画从元素的当前位置开始,在这种情况下:从右边70%的第一次单击和从动画之后的元素位置的第二次单击开始。 (代码将不胜感激)

$(document).ready(function(){
	$( "button" ).click(function(){
             screenWidth = Math.round($("html").width() /2)
	     positionLeft = Math.round($(".container").offset().left)	
					 
		if ( positionLeft < screenWidth) {		
      $(".container").css('right', "auto");  
	    $(".container").animate({
			left: "50%"
			}, 1000);
		} else if (positionLeft == screenWidth) {		  
			$(".container").css('left', "auto");
			$(".container").animate({
			right: "50%"
			}, 1000); 	
		}
	});
	
});
  .container{
		background-color:black;
		height: 50%;
		width: 20%;
		position: absolute;
		top: 30%;	
		right :70%;			
  }		
<!doctype html>
<html>
<head>
<title>debugging</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>

<body>
  <div class="container"></div>         
  <button>click</button> 
</body>
</html>

1 个答案:

答案 0 :(得分:0)

在按钮上单击,您希望为left选择器设置动画,因此您将%设置为自动(左侧%也保留为自动),这会将元素跳转到左边距 - 它将在左侧/左侧右边都设置为自动。然后动画开始。

有几种方法可以解决这个问题。一种是仅对右选择器进行动画处理,而不是左对齐(请参阅答案最底部的jsFiddle演示)。

另一种是交换它们。您只需将right设置为自动 - 左侧也是auto。您必须设置为自动左至10%(即100-70 = 30%减去容器宽度20%,等于10%)。我在回答嵌入式代码中这样做,以向您显示当您在第三次按钮单击时切换回动画正确的百分比时,会发生同样的问题。

最佳解决方案是使用一个选择器(左或右)为所有内容设置动画。选择一个并坚持下去。

&#13;
&#13;
$(document).ready(function(){
	$( "button" ).click(function(){
             screenWidth = Math.round($("html").width() /2)
	     positionLeft = Math.round($(".container").offset().left)	
					 
		if ( positionLeft < screenWidth) {		
      $(".container").css({'right':"auto", 'left':'10%'});  
	    $(".container").animate({
			left: "50%"
			}, 1000);
		} else if (positionLeft == screenWidth) {		  
			$(".container").css({'left':"auto", 'right':'30%'});
			$(".container").animate({
			right: "50%"
			}, 1000); 	
		}
	});
	
});
&#13;
  .container{
		background-color:black;
		height: 50%;
		width: 20%;
		position: absolute;
		top: 30%;	
		right :70%;			
  }		
&#13;
<!doctype html>
<html>
<head>
<title>debugging</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>

<body>
  <div class="container"></div>         
  <button>click</button> 
</body>
</html>
&#13;
&#13;
&#13;


这里只使用正确的选择器动画:jsfiddle Demo