jquery从顶部滚动到px计数,然后设置一个div从顶部固定为滚动的其余部分 [英] jquery scroll to a px count from top and then set a div to be fixed from the top for the rest of the scroll

查看:107
本文介绍了jquery从顶部滚动到px计数,然后设置一个div从顶部固定为滚动的其余部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向页面的某个点滚动时,我想要更改div的css,从页面顶部开始有一定数量的像素。

I am looking to change a div's css when i scroll to a certain point down the page, a certain amount of pixels from the top of the page.

On页面加载我将有一个静态定位div。一旦我开始向下滚动页面并从顶部点击一个点(比如100px用于演示目的),我想将该静态div更改为从顶部固定为20px。这将通过jquery的css()属性完成。这将允许它在页面下方保持固定的20px。

On page load i would have a div positioned statically. Once I started to scroll down the page and i hit a point from the top (say 100px for demo purposes) i want to change that static div to become fixed like 20px from the top. Which would be done via the css() property of jquery. THis would allow it to stay at that fixed 20px all the way down the page.

当我达到100px标记时,我可以使用什么jquery属性来知道。一旦有人回到顶部,我希望这也恢复,以便div被放回到页面加载时的位置,而不是从顶部开始的20px。

What jquery property can i use to know when i hit that 100px mark. I want this to also revert once someone gets back to the top so that the div is put back to where it was when the page loaded and not 20px from the top.

任何想法?

推荐答案

你可以使用运行代码的 scroll()事件,以及 scrollTop()方法查看你的位置。

You could use the scroll() event to run the code, and the scrollTop() method to see where you are.

这是一个演示: http://jsfiddle.net/EahRx/

(我使用了您提供的值,因此有一个跳跃。我相信它会在您的实际页面中看起来更好。)

var fixed = false;

$(document).scroll(function() {
    if( $(this).scrollTop() >= 100 ) {
        if( !fixed ) {
            fixed = true;
            $('#myDiv').css({position:'fixed',top:20}); // Or set top:20px; in CSS
        }                                           // It won't matter when static
    } else {
        if( fixed ) {
            fixed = false;
            $('#myDiv').css({position:'static'});
        }
    }
});

修复变量阻止 .css()代码运行次数超过需要的时间。

The fixed variable prevents the .css() code from running more times than it needs to.

这篇关于jquery从顶部滚动到px计数,然后设置一个div从顶部固定为滚动的其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆