滚动到后,如何使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);
        }
    });
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值