javascript 如何使用 jQuery 为固定元素的位置设置动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29034187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:59:34  来源:igfitidea点击:

How to animate a position of a fixed element with jQuery

javascriptjqueryhtmlcssanimation

提问by Mostafa Talebi

I have a div whose position properties is:

我有一个 div,其位置属性是:

.some
{
    position: fixed;
    top: 0px;
}

I then want to animate its bottom(not with top, with bottomproperty)

然后我想对其进行动画处理bottom(不使用top,使用bottom属性)

$(document).ready(function(){

                  $("a").on("click", function(e){
    e.preventDefault();
                      $("div").animate({ top: "none", bottom : 25});    
        });
});

But it does not work. The problem is that topproperty is in the priority. If I set the top to 0 then it sticks to the top, it does not care any to bottom value. However I remove the top property and animate bottom, it starts the animation right from the very bottom. I want the animation to start from the position which is designated by top value and end in where it is specified by bottom value. What should I do?

但它不起作用。问题是top财产是优先的。如果我将顶部设置为 0,那么它会粘在顶部,它不关心任何到底部的值。但是我删除了 top 属性并为底部设置了动画,它从最底部开始动画。我希望动画从顶部值指定的位置开始,并在底部值指定的位置结束。我该怎么办?

Here is the JSFiddle:

这是 JSFiddle:

http://jsfiddle.net/mostafatalebi2/ex1b69g9/

http://jsfiddle.net/mostafatalebi2/ex1b69g9/

回答by Marco Bonelli

You should animate from top: 0to top: 100%using a negative margin-topvalue to maintain the divat a certain distance from the bottom of the page. Doing so, your divwill move from the very top to the bottom of the page, like you want.

你应该从动画top: 0top: 100%使用负margin-top值保持div在从页面底部有一定的距离。这样做,div将从页面的最顶部移动到底部,就像您想要的那样。

To move your div exactly 25 pixelsdistant from the bottom you can set margin-topto the negative value of your div's height minus 25px.

要将您的 div25 pixels与底部完全远离,您可以margin-topdiv 的高度设置为负值减去25px

Here's an example:

下面是一个例子:

$(document).ready(function() {
    $("a").on("click", function(e) {
        e.preventDefault();
        var $div = $('div.some');
        $div.animate({
            top: '100%',
            marginTop: - $div.height() - 25
        });
    });
});
.some {
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class='some'>I am a DIV!</div>
<br/>
<br/>
<a href='#'>Click Here!</a>

回答by EddNewGate

$(document).ready(function(){

                  $("a").on("click", function(e){
    e.preventDefault();
                      $("div").animate({ top:'500px'});    
        });
});

Fiddle: http://jsfiddle.net/gcsx1exj/1/

小提琴:http: //jsfiddle.net/gcsx1exj/1/