滚动到后,如何使div停留在屏幕顶部?

本文翻译自:How can I make a div stick to the top of the screen once it's been scrolled to?

我想创建一个div,它位于内容块的下面,但是一旦页面滚动到足以接触其顶部边界的位置,它就会固定在适当的位置并随页面滚动。


#1楼

参考:https://stackoom.com/question/56mK/滚动到后-如何使div停留在屏幕顶部


#2楼

You could use simply css, positioning your element as fixed : 您可以简单地使用css,将元素定位为fixed

.fixedElement {
    background-color: #c0c0c0;
    position:fixed;
    top:0;
    width:100%;
    z-index:100;
}

Edit: You should have the element with position absolute, once the scroll offset has reached the element, it should be changed to fixed, and the top position should be set to zero. 编辑:您应该将元素的位置设为绝对,一旦滚动偏移量到达该元素,则应将其更改为fixed,并将顶部位置设置为零。

You can detect the top scroll offset of the document with the scrollTop function: 您可以使用scrollTop函数检测文档的顶部滚动偏移量:

$(window).scroll(function(e){ 
  var $el = $('.fixedElement'); 
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 200 && !isPositionFixed){ 
    $el.css({'position': 'fixed', 'top': '0px'}); 
  }
  if ($(this).scrollTop() < 200 && isPositionFixed){
    $el.css({'position': 'static', 'top': '0px'}); 
  } 
});

When the scroll offset reached 200, the element will stick to the top of the browser window, because is placed as fixed. 当滚动偏移量达到200时,该元素将固定在浏览器窗口的顶部,因为它的位置固定。


#3楼

The info provided to answer this other question may be of help to you, Evan: Evan提供的回答其他问题的信息可能会对您有所帮助:

Check if element is visible after scrolling 滚动后检查元素是否可见

You basically want to modify the style of the element to set it to fixed only after having verified that the document.body.scrollTop value is equal to or greater than the top of your element. 您基本上想修改元素的样式,以仅在验证document.body.scrollTop值等于或大于元素的顶部之后将其设置为固定。


#4楼

My solution is a little verbose, but it handles variable positioning from the left edge for centered layouts. 我的解决方案有些冗长,但是它可以处理居中布局从左边缘开始的可变位置。

// Ensurs that a element (usually a div) stays on the screen
//   aElementToStick   = The jQuery selector for the element to keep visible
global.makeSticky = function (aElementToStick) {
    var $elementToStick = $(aElementToStick);
    var top = $elementToStick.offset().top;
    var origPosition = $elementToStick.css('position');

    function positionFloater(a$Win) {
        // Set the original position to allow the browser to adjust the horizontal position
        $elementToStick.css('position', origPosition);

        // Test how far down the page is scrolled
        var scrollTop = a$Win.scrollTop();
        // If the page is scrolled passed the top of the element make it stick to the top of the screen
        if (top < scrollTop) {
            // Get the horizontal position
            var left = $elementToStick.offset().left;
            // Set the positioning as fixed to hold it's position
            $elementToStick.css('position', 'fixed');
            // Reuse the horizontal positioning
            $elementToStick.css('left', left);
            // Hold the element at the top of the screen
            $elementToStick.css('top', 0);
        }
    }

    // Perform initial positioning
    positionFloater($(window));

    // Reposition when the window resizes
    $(window).resize(function (e) {
        positionFloater($(this));
    });

    // Reposition when the window scrolls
    $(window).scroll(function (e) {
        positionFloater($(this));
    });
};

#5楼

I used some of the work above to create this tech. 我使用上面的一些工作来创建这项技术。 I improved it a bit and thought I would share my work. 我做了一些改进,以为我可以分享我的工作。 Hope this helps. 希望这可以帮助。

jsfuddle Code jsfuddle代码

function scrollErrorMessageToTop() {
    var flash_error = jQuery('#flash_error');
    var flash_position = flash_error.position();

    function lockErrorMessageToTop() {
        var place_holder = jQuery("#place_holder");
        if (jQuery(this).scrollTop() > flash_position.top && flash_error.attr("position") != "fixed") {
            flash_error.css({
                'position': 'fixed',
                'top': "0px",
                "width": flash_error.width(),
                "z-index": "1"
            });
            place_holder.css("display", "");
        } else {
            flash_error.css('position', '');
            place_holder.css("display", "none");
        }

    }
    if (flash_error.length > 0) {
        lockErrorMessageToTop();

        jQuery("#flash_error").after(jQuery("<div id='place_holder'>"));
        var place_holder = jQuery("#place_holder");
        place_holder.css({
            "height": flash_error.height(),
            "display": "none"
        });
        jQuery(window).scroll(function(e) {
            lockErrorMessageToTop();
        });
    }
}
scrollErrorMessageToTop();​

This is a little bit more dynamic of a way to do the scroll. 这种滚动方式更具动态性。 It does need some work and I will at some point turn this into a pluging but but this is what I came up with after hour of work. 它确实需要做一些工作,我会在某个时候将其转换为一个插件,但这就是我在工作一个小时后想到的。


#6楼

This is how i did it with jquery. 这就是我用jquery做到的方式。 This was all cobbled together from various answers on stack overflow. 这些都是从堆栈溢出的各种答案中总结出来的。 This solution caches the selectors for faster performance and also solves the "jumping" issue when the sticky div becomes sticky. 此解决方案缓存选择器以提高性能,还解决了粘性div变为粘性时的“跳转”问题。

Check it out on jsfiddle: http://jsfiddle.net/HQS8s/ 在jsfiddle上检查一下: http : //jsfiddle.net/HQS8s/

CSS: CSS:

.stick {
    position: fixed;
    top: 0;
}

JS: JS:

$(document).ready(function() {
    // Cache selectors for faster performance.
    var $window = $(window),
        $mainMenuBar = $('#mainMenuBar'),
        $mainMenuBarAnchor = $('#mainMenuBarAnchor');

    // Run this on scroll events.
    $window.scroll(function() {
        var window_top = $window.scrollTop();
        var div_top = $mainMenuBarAnchor.offset().top;
        if (window_top > div_top) {
            // Make the div sticky.
            $mainMenuBar.addClass('stick');
            $mainMenuBarAnchor.height($mainMenuBar.height());
        }
        else {
            // Unstick the div.
            $mainMenuBar.removeClass('stick');
            $mainMenuBarAnchor.height(0);
        }
    });
});
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、遇顶固定的例子 我一直以为是某个div或层随屏幕滚动,遇顶则固定,离开浏览器顶部又还原这样的例子其实不少,其实它的名字叫“层的智能浮动效果”。目前我们在国内的商业网站上就常常看到这样的效果了。例如淘宝网的搜索结果页的排序水平条,在默认状态时,该工具条是跟随页面滚动的,如下图: 而当我们下拉滚动条,随着页面向下滚动,当此工具条接触到浏览器的上边缘时,这时就会独立出来固定顶部,不跟随页面滚动滚动了,如下图: 类似的例子效果我们在别的网站上都有看到过,例如腾讯微博首页上,当我们下拉屏幕浏览最新微博时,工具条也会出现这个效果,如下图: 这个效果看上去方便,贴心,也许还带推动广告的促销呢。原理其实很简单,本文展示两种方法。 二、智能浮动效果的实现原理 它分两种状态,一是默认状态,二是浮动固顶状态。 默认状态就是默认状态,什么也不用做,保持原有的CSS就好。无论有没有对它做定位,做了absolute也好,没做也好,都行。 关键是当浏览器屏幕滚动时,该对象div层要移除浏览器界面视区的时候,是要修改它的position属性,让它浮动在窗口的上沿显示就行了。最好的position属性是fixed,可以在IE6+和其他浏览器浮动层平滑的固定定位,由于IE6老大哥不支持fixed属性,所以可以另外赋予它absolute属性。当然也会产生副作用——滚动不平滑。不过也无所谓了,在微软公布不再修补更新XP漏洞,在中国360安全卫士的帮助下虽然大家仍然使用XP,但IE的用户已经是少之又少了。 那接下来,如何判断当前div层与浏览器窗口的上边缘接触了呢?遇到浏览器顶部了呢? 当浮动层div与浏览器窗口上边缘接触的一瞬间,其页面垂直偏移值与页面的滚动高度是一致的,所以我们就用这个进行判断。那如何获得页面上元素距离页面的垂直距离呢? 这里则是使用javaScript库实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值