【问题标题】:Replace a Jquery .animate with a 0 time to something more efficient将 Jquery .animate 替换为 0 时间以提高效率
【发布时间】:2013-05-29 04:54:09
【问题描述】:

我最近一直在网站上使用此设置...

http://jsfiddle.net/mnRNE/

CSS

body {
 height:2000px;   
}

#top-box {
 position:fixed;
 width:200px;
 height:200px;
 margin-left:100px;
 margin-top:50px;
 background-color:blue;   
 z-index:2;   
}

#bottom-box {
 position:fixed;
 width:200px;
 height:200px;
 margin-left:110px;
 margin-top:60px;
 background-color:red;  
 z-index:1;    

}

JavaScript

$(document).ready(function() {
    var away = false;

 $(document).scroll(function() {
    if ($(document).scrollTop() > 250) {
        if (!away) {
            away = true;
            $('#bottom-box').stop().animate({
                'margin-top': '200px'
            }, 1500);
        }
    } else {
        away = false;
        $('#bottom-box').stop().animate({
            'margin-top': '60px'
        }, 0);
    }
});
});

HTML

<div id="top-box"></div>
<div id="bottom-box"></div>

这样一旦用户向下滚动页面 250 像素,红色框就会动画并从蓝色框下方滑出。第一个动画是定时的,因此过渡很明显(红色框明显滑出)。

然后设置,如果用户向后滚动到 250 像素以上,红色框会移回蓝色框下方。这是在没有计时器的情况下完成的,因此转换是即时的(红色框会弹回原来的位置)。

这很好用,可以做我需要做的一切。但我很好奇是否有更好的方法来实现第二个动画,根本不使用动画,只需将红色框“重置”为“margin-top:60px”,而无需计时或 .animate ?

基本上,我问的是...

        $('#bottom-box').stop().animate({
            'margin-top': '60px'
        }, 0);

JavaScript 的部分可以用不同的方式编写并且更有效地实现相同的结果但不使用动画?就像一种“将 'bottom-box' 设置为 'margin-top': '60px'”?

【问题讨论】:

    标签: jquery css jquery-animate


    【解决方案1】:
    $('#bottom-box').stop().css({ 
            'margin-top': '60px' 
        }); 
    

    【讨论】:

    • 这里一样,这不起作用,请参阅对 danwellman 答案的评论。
    • @Tim 它确实有效,您的答案甚至与此重复?
    • 这不起作用。但是,如果 { 和 } 在 'margin-top': '60px' 之前和之后被删除,它似乎工作正常。
    • 有了这个你可以使用多个css规则,比如: .css({'margin-top': '60px','display':'block'});只有这个:.css('margin-top', '60px');两者都可以工作
    【解决方案2】:

    我认为使用 jquery .css 更整洁

    http://jsfiddle.net/mnRNE/1/

            $('#bottom-box').stop().css('marginTop', '60px'); 
    

    成功了

    【讨论】:

    • 完美运行,如果我使用 'margin-top' 而不是 'marginTop' 似乎也可以。有什么理由我应该使用一个而不是另一个?
    • 我以为我在 CSS 手册中看到了一些解释这一点的东西,请参阅对 danwellman 的评论,但它仅用于检索元素,我错误地认为它是用于获取 CSS 的两种设置。所以 margin-top 和 marginTop 都可以正常工作!
    【解决方案3】:

    为什么不

    $('#bottom-box').css('margin-top', '60px');
    

    【讨论】:

    • 这将不起作用,因为 Jquery 从 jQuery 手册中阻止了这一点:不支持速记 CSS 属性(例如边距、背景、边框)。例如,如果要检索渲染的边距,请使用:$(elem).css('marginTop') 和 $(elem).css('marginRight'),等等。
    • 这半部分有效,在 Firefox 和 Chome 中,只要第一个动画完成,它就有效,但如果用户向上滚动中间动画,红框不会重置位置。如果在 IE、Opera 或 Safari 中查看,它似乎工作正常。
    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2020-09-19
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多