我试图通过将 css top 值设置为 0px 并将它的 css 属性从 relative 更改为 fixed(它覆盖了它上面的另一个 div)来让一个 div 动画到窗口的顶部。属性发生变化,但它不会动画化到顶部,它只是在一帧中出现。我真的很想轻松到达顶部而不是跳跃。
这是一个 fiddle http://jsfiddle.net/sedickinson/d4c9u/
下面的代码
HTML
<html>
<head>
<style>
#menu{
position: relative ; background-color: black; color: white;
text-align: center; width:100%; z-index: 9
}
#space{height:20px; position: relative; z-index: 5}
</style>
</head>
<body>
<div id="space"> </div>
<div id="menu">blah</div>
<script>
var menu = $("#menu");
menu.css('position','fixed').delay(400);
menu.animate({top: '0px'},1000);
</script>
</body>
</html>
最佳答案
问题是,在您将位置更改为 fixed 之前,元素没有设置“top”值。它设置为自动。您可以先将其设置为 offsetTop 值,然后将位置更改为固定,然后为其设置动画,如下所示:
var menu = $("#menu");
menu.css({'top': menu.offset().top, 'position': 'fixed'})
.delay(400).animate({top: '0'},1000);
基本上,您不能将它从“自动”设置为“0”。
关于javascript - 无法使用 jquery 将 div 顶部属性设置为 0px,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21070540/