【问题标题】:CSS bottom transition not smoothCSS底部过渡不平滑
【发布时间】:2016-05-03 12:57:24
【问题描述】:

$(function(){
	
	function boxtoRight(){
		$("#box").animate({marginLeft: 600},3000,'linear',boxtoLeft);
	}
	function boxtoLeft(){
		$("#box").animate({marginLeft: 0},3000,'linear',boxtoRight);
	}
	boxtoRight();


	$(document).keydown(function(e){
		if(e.keyCode == 32){
			$("#box").css("background","green");
			$("#box").css("bottom","200px").css("transition","0.2s");
		}
	});
	$(document).keyup(function(e){ 
		if(e.keyCode == 32){
			$("#box").css("background","red");
			$("#box").css("bottom","130px").css("transition","0.2s");
		}
	});

});
#container{
	background: #ccc;
	width: 600px;
	height: 200px;
}
#box{
	width: 90px;
	height: 90px;
	background: red;
	position: absolute;
	margin-top: 110px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
		<div id="box"></div>
</div>

问题是当我按下空格键时我试图让框跳起来。现在如果我按空格键,框会跳,但动画不流畅。

另外,如何通过动画,滚动和转到文档右侧将框移动到窗口的中心?

【问题讨论】:

  • 我不确定您所说的“使用动画将框移动到窗口屏幕的中心,滚动并转到文档右侧”是什么意思。如果你更清楚地解释你想要什么,我可以更新我的答案。
  • 框从左到右开始时始终位于屏幕中心,就像马里奥一样。

标签: jquery scroll jquery-animate css-transitions


【解决方案1】:

这里有几件事。在 CSS 过渡属性中,您需要指定过渡适用于哪个属性。所以我更新了你的 CSS 以包含 transition: bottom 0.2。我还给了#container position: relative 所以#boxbottom 属性相对于#container 的底部。

#container{
    background: #ccc;
    width: 600px;
    height: 200px;
    position: relative; //added
}    

#box{
    width: 90px;
    height: 90px;
    background: red;
    position: absolute;
    bottom: 0px;  //added
    transition: bottom 0.2s; //added
}

现在在您的 Javascript 中,您不再需要更改 transition 属性。此外,我没有多次调用.css(),而是在一次.css() 调用中更改了多个属性。最后,我更改了bottom 的值,因为它现在相对于#container 的底部。

$(function(){

    function boxtoRight(){
        $("#box").animate({marginLeft: 510 },3000,'linear',boxtoLeft);
    }
    function boxtoLeft(){
        $("#box").animate({marginLeft: 0},3000,'linear',boxtoRight);
    }
    boxtoRight();


    $(document).keydown(function(e){
        if(e.keyCode == 32){
            $("#box").css({"background":"green",
                           "bottom":"70px"
            });
        }
    });
    $(document).keyup(function(e){ 
        if(e.keyCode == 32){
            $("#box").css({"background":"red",
                           "bottom":"0px"
            });
         }
     });
});

看看这个工作小提琴:https://jsfiddle.net/s3pfrhn8/2/

【讨论】:

  • 谢谢,它的工作,有没有可能当盒子跳1秒(按住空格键)可以让盒子放下?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2013-07-19
  • 1970-01-01
  • 2016-10-07
  • 2014-05-25
  • 1970-01-01
  • 2023-02-10
相关资源
最近更新 更多