滚动时固定/浮动div元素元素、div

2023-09-10 13:18:53 作者:独饮这杯烈酒〆

我试图寻找这个在网络上,但我不知道要寻找什么究竟。我试图找出如何创建一个将固定一个div元素,或浮动只在元素的顶部到达窗口浏览器视图的顶部。例如,如果一个元素是页面的半路上,当你继续向下滚动,该元素将留在原地,直到它的即将消失的话,那就要留在我的浏览器(固定)的顶部。

I'm trying to search for this on the web, but I'm not sure what to look for exactly. I'm trying to find out how to create a div element that will be fixed, or float ONLY when the TOP of the element reaches the TOP of the window browser view. For instance, if an element is half way of the page, when you continue to scroll down, that element will stay put UNTIL its about to disappear, then it would want to stay at the top of my browser (fixed).

推荐答案

我觉得我做类似于你想做什么事情。试试下面的code,把任何你需要在通知DIV和离开主播单独一种。

I think I'm doing something similar to what you want to do. Try out the following code, put whatever you need in notification div and leave the anchor one alone.

<div id="notification-anchor"></div>
<div id="notification"></div>

<script type="text/javascript"> 
    $(function() {
        var a = function() {
            var b = $(window).scrollTop();
            var d = $("#notification-anchor").offset().top;
            var c = $("#notification");
            if (b > d) {
                c.css({position:"fixed",top:"0px"})
            } else {
                c.css({position:"absolute",top:""})
            }
        };
        $(window).scroll(a);a()
    });
</script> 

编辑:你要注意,这需要你有JQuery的,如果这不是明摆着你

You should note, this requires you to include JQuery if that's not obvious to you.