滚动上的 jQuery 动画 div

标签 jquery css

我有这个

$(document).ready(function(){
$(window).scroll(function(){
   if($("#1").offset().top < $(window).scrollTop());
    $("#1").animate({"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"}, 1000);
}, function() {
$("#1").animate({"color":"#333","font-size":"52pt", "top":"0", "position":"fixed"}, 1000);
  });
});

jsfiddle如您所见,当您开始滚动时,文本会显示动画(我确实从 Stackoverflow 获得了这个,但丢失了链接,所以感谢为第一篇文章做出贡献的人)我想要的是让文本动画回来当内容再次到达顶部时恢复到原来的状态。

非常感谢任何帮助

亲切的问候

最佳答案

您需要什么样的浏览器支持?动画背部的问题是你需要知道原来的风格。

Once 我能想到的方法是使用 window.getComputedStyle 方法检索元素的样式并将它们存储在对象数组中以用于动画返回。您将需要一些额外的支持功能。

我在 Chrome、IE 9 和 FireFox 24 中测试了以下代码,它似乎运行良好。这完全取决于您使用的风格。但是,由于您正在制作动画,因此这应该适用于大多数情况。

此外,我将您的样式和速度存储在变量中以使其更清晰。下面的 fiddle :

$(document).ready(function(){
    var aniCss = {"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"};
    var speed = 1000;
    var props = getProps(aniCss);
    var curCss = getStyles($("#1"), props);
    $(window).scroll(function(){
        if ($(window).scrollTop() >0) {
            $("#1").animate(aniCss,speed);
        }
        else {
            $("#1").stop(true,true).animate(curCss,speed);
        }
    });

    function getProps(css) {
        var props = [];
        for (k in css) {
            props.push(k);
        }
        return props;
    }
    function getStyles($ele, props) {
        var compCss = getComputedStyle($ele[0]);
        var styles = {};
        for (var i = 0;i<props.length;i++) {
            var name = props[i];
            var prop = compCss.getPropertyValue(name);
            if (prop != '') { styles[name]=prop;}
        }
        return styles;
    }
});

fiddle :http://jsfiddle.net/ajqQL/1/

更新:刚刚看到在 jQuery 1.9 中他们添加了传递属性数组以检索值的能力。您可以仅使用 jQuery .css() 方法来简化上述内容:

$(document).ready(function(){
    var aniCss = {"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"};
    var speed = 400;
    var props = getProps(aniCss);
    var curCss = $('#1').css(props);
    $(window).scroll(function(){
        if ($(window).scrollTop() >0) {
            $("#1").animate(aniCss,speed);
        }
        else {
            $("#1").stop(true,true).animate(curCss,speed);
        }
    });

    function getProps(css) {
        var props = [];
        for (k in css) {
            props.push(k);
        }
        return props;
    }
});

fiddle :http://jsfiddle.net/NZq8D/1/

关于滚动上的 jQuery 动画 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821494/

相关文章:

jquery - 将数据从桌面附加到 bootgrid 时搜索被破坏

javascript - 如何在 Canvas 中绘制从页面加载的图像

javascript - 通过 javascript 将 json 对象发送到 python Web 服务

jquery - 使用JQuery根据子div背景颜色隐藏父li

javascript - POST 到外部 URL (webhook) 但重定向到不同的 URL

html - 设置宽度 :100% relative to another object for an object that needs to be fixed

javascript - 按下按钮时文本框不更新

jquery - 滚动触发的动画极度延迟

css - 为 SVG 路径的一部分着色

html - 使用跨度创建表