如何让 div 在滚动到屏幕顶部后粘在屏幕顶部?

发布于 2024-07-30 01:55:48 字数 64 浏览 3 评论 0原文

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

I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place and scrolls with the page.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(27

水中月 2024-08-06 01:55:49

不是一个精确的解决方案,而是考虑的一个很好的替代方案

CSS ONLY Top of screen滚动条。 使用仅CSS解决了所有问题,没有 JavaScript,没有 JQuery,没有脑力劳动(哈哈)。

享受 我的小提琴 :D 所有代码都包含在其中:)

CSS

#menu {
position: fixed;
height: 60px;
width: 100%;
top: 0;
left: 0;
border-top: 5px solid #a1cb2f;
background: #fff;
-moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
-webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
z-index: 999999;
}

.w {
    width: 900px;
    margin: 0 auto;
    margin-bottom: 40px;
}<br type="_moz">

将内容放得足够长,以便您可以在这里看到效果:)

哦,参考资料也在那里,因为他值得 他的功劳

CSS 仅屏幕顶部滚动条

Not an exact solution but a great alternative to consider

this CSS ONLY Top of screen scroll bar. Solved all the problem with ONLY CSS, NO JavaScript, NO JQuery, No Brain work (lol).

Enjoy my fiddle :D all the codes are included in there :)

CSS

#menu {
position: fixed;
height: 60px;
width: 100%;
top: 0;
left: 0;
border-top: 5px solid #a1cb2f;
background: #fff;
-moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
-webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
z-index: 999999;
}

.w {
    width: 900px;
    margin: 0 auto;
    margin-bottom: 40px;
}<br type="_moz">

Put the content long enough so you can see the effect here :)

Oh, and the reference is in there as well, for the fact he deserve his credit

CSS ONLY Top of screen scroll bar

ペ泪落弦音 2024-08-06 01:55:49

接受的答案有效,但如果您滚动到它上面,则不会移回之前的位置。 放在上面后总是粘在上面。

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

    } else if ($(this).scrollTop() < 42 && $el.css('position') != 'relative') {
      $('.fixedElement').css( 'relative': 'fixed', 'top': '42px');
//this was just my previous position/formating
    }
  });

jleedev 的回应应该有效,但我无法让它发挥作用。 他的示例页面也不起作用(对我来说)。

The accepted answer works but doesn't move back to previous position if you scroll above it. It is always stuck to the top after being placed there.

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

    } else if ($(this).scrollTop() < 42 && $el.css('position') != 'relative') {
      $('.fixedElement').css( 'relative': 'fixed', 'top': '42px');
//this was just my previous position/formating
    }
  });

jleedev's response whould work, but I wasn't able to get it to work. His example page also didn't work (for me).

美煞众生 2024-08-06 01:55:49

粘性直到页脚碰到 div:

function stickyCostSummary() {
    var stickySummary = $('.sticky-cost-summary');
    var scrollCostSummaryDivPosition = $(window).scrollTop();
    var footerHeight = $('#footer').height();
    var documentHeight = $(document).height();
    var costSummaryHeight = stickySummary.height();
    var headerHeight = 83;
    var footerMargin = 10;
    var scrollHeight = 252;
    var footerPosition = $('#footer').offset().top;

    if (scrollCostSummaryDivPosition > scrollHeight && scrollCostSummaryDivPosition <= (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
        stickySummary.removeAttr('style');
        stickySummary.addClass('fixed');

    } else if (scrollCostSummaryDivPosition > (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
        stickySummary.removeClass('fixed');
        stickySummary.css({
          "position" : "absolute",
          "top" : (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin - scrollHeight) + "px"
      });
    } else {
        stickySummary.removeClass('fixed');
        stickySummary.css({
            "position" : "absolute",
            "top" : "0"
        });
    }
}

$window.scroll(stickyCostSummary);

sticky till the footer hits the div:

function stickyCostSummary() {
    var stickySummary = $('.sticky-cost-summary');
    var scrollCostSummaryDivPosition = $(window).scrollTop();
    var footerHeight = $('#footer').height();
    var documentHeight = $(document).height();
    var costSummaryHeight = stickySummary.height();
    var headerHeight = 83;
    var footerMargin = 10;
    var scrollHeight = 252;
    var footerPosition = $('#footer').offset().top;

    if (scrollCostSummaryDivPosition > scrollHeight && scrollCostSummaryDivPosition <= (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
        stickySummary.removeAttr('style');
        stickySummary.addClass('fixed');

    } else if (scrollCostSummaryDivPosition > (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
        stickySummary.removeClass('fixed');
        stickySummary.css({
          "position" : "absolute",
          "top" : (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin - scrollHeight) + "px"
      });
    } else {
        stickySummary.removeClass('fixed');
        stickySummary.css({
            "position" : "absolute",
            "top" : "0"
        });
    }
}

$window.scroll(stickyCostSummary);
疏忽 2024-08-06 01:55:49

您所要做的就是 position:fixed;top: 0px; 就这么简单。 我在我的网络应用程序中使用它。

All you have to do is position: fixed; and top: 0px; Its so simple. I use it in my web app.

北城半夏 2024-08-06 01:55:49

您可以添加 3 行额外的行,这样当用户滚动回顶部时,div 将停留在原来的位置:

代码如下:

if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed'){
    $('.fixedElement').css({'position': 'relative', 'top': '200px'});
}

You can add 3 extra rows so when the user scroll back to the top, the div will stick on its old place:

Here is the code:

if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed'){
    $('.fixedElement').css({'position': 'relative', 'top': '200px'});
}
陪我终i 2024-08-06 01:55:49

我在 div 中设置了链接,因此它是字母和数字链接的垂直列表。

#links {
    float:left;
    font-size:9pt;
    margin-left:0.5em;
    margin-right:1em;
    position:fixed;
    text-align:center;
    width:0.8em;
}

然后,我设置这个方便的 jQuery 函数来保存加载的位置,然后在滚动超出该位置时将位置更改为固定。

注意:仅当链接在页面加载时可见时才有效!

var listposition=false;
jQuery(function(){
     try{
        ///// stick the list links to top of page when scrolling
        listposition = jQuery('#links').css({'position': 'static', 'top': '0px'}).position();
        console.log(listposition);
        $(window).scroll(function(e){
            $top = $(this).scrollTop();
            $el = jQuery('#links');
            //if(typeof(console)!='undefined'){
            //    console.log(listposition.top,$top);
            //}
            if ($top > listposition.top && $el.css('position') != 'fixed'){
                $el.css({'position': 'fixed', 'top': '0px'});
            }
            else if ($top < listposition.top && $el.css('position') == 'fixed'){
                $el.css({'position': 'static'});
            }
        });

    } catch(e) {
        alert('Please vendor [email protected] (Myvendor JavaScript Issue)');
    }
});

I have links setup in a div so it is a vertical list of letter and number links.

#links {
    float:left;
    font-size:9pt;
    margin-left:0.5em;
    margin-right:1em;
    position:fixed;
    text-align:center;
    width:0.8em;
}

I then setup this handy jQuery function to save the loaded position and then change the position to fixed when scrolling beyond that position.

NOTE: this only works if the links are visible on page load!!

var listposition=false;
jQuery(function(){
     try{
        ///// stick the list links to top of page when scrolling
        listposition = jQuery('#links').css({'position': 'static', 'top': '0px'}).position();
        console.log(listposition);
        $(window).scroll(function(e){
            $top = $(this).scrollTop();
            $el = jQuery('#links');
            //if(typeof(console)!='undefined'){
            //    console.log(listposition.top,$top);
            //}
            if ($top > listposition.top && $el.css('position') != 'fixed'){
                $el.css({'position': 'fixed', 'top': '0px'});
            }
            else if ($top < listposition.top && $el.css('position') == 'fixed'){
                $el.css({'position': 'static'});
            }
        });

    } catch(e) {
        alert('Please vendor [email protected] (Myvendor JavaScript Issue)');
    }
});
我们的影子 2024-08-06 01:55:49

在 JavaScript 中你可以这样做:

var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";

In javascript you can do:

var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";
番薯 2024-08-06 01:55:49

下面是一个使用 jquery-visible 插件的示例:http://jsfiddle.net/711p4em4/

HTML:

<div class = "wrapper">
    <header>Header</header>
    <main>
        <nav>Stick to top</nav>
        Content
    </main>
    <footer>Footer</footer>
</div>

CSS:

* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #e2e2e2;
}

.wrapper > header,
.wrapper > footer {
    font: 20px/2 Sans-Serif;
    text-align: center;
    background-color: #0040FF;
    color: #fff;
}

.wrapper > main {
    position: relative;
    height: 500px;
    background-color: #5e5e5e;
    font: 20px/500px Sans-Serif;
    color: #fff;
    text-align: center;
    padding-top: 40px;
}

.wrapper > main > nav {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    font: 20px/2 Sans-Serif;
    color: #fff;
    text-align: center;
    background-color: #FFBF00;
}

.wrapper > main > nav.fixed {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}

JS (包括 jquery-visible 插件):

(function($){

    /**
     * Copyright 2012, Digital Fusion
     * Licensed under the MIT license.
     * http://teamdf.com/jquery-plugins/license/
     *
     * @author Sam Sehnert
     * @desc A small plugin that checks whether elements are within
     *       the user visible viewport of a web browser.
     *       only accounts for vertical position, not horizontal.
     */
    var $w = $(window);
    $.fn.visible = function(partial,hidden,direction){

        if (this.length < 1)
            return;

        var $t        = this.length > 1 ? this.eq(0) : this,
            t         = $t.get(0),
            vpWidth   = $w.width(),
            vpHeight  = $w.height(),
            direction = (direction) ? direction : 'both',
            clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

        if (typeof t.getBoundingClientRect === 'function'){

            // Use this native browser method, if available.
            var rec = t.getBoundingClientRect(),
                tViz = rec.top    >= 0 && rec.top    <  vpHeight,
                bViz = rec.bottom >  0 && rec.bottom <= vpHeight,
                lViz = rec.left   >= 0 && rec.left   <  vpWidth,
                rViz = rec.right  >  0 && rec.right  <= vpWidth,
                vVisible   = partial ? tViz || bViz : tViz && bViz,
                hVisible   = partial ? lViz || rViz : lViz && rViz;

            if(direction === 'both')
                return clientSize && vVisible && hVisible;
            else if(direction === 'vertical')
                return clientSize && vVisible;
            else if(direction === 'horizontal')
                return clientSize && hVisible;
        } else {

            var viewTop         = $w.scrollTop(),
                viewBottom      = viewTop + vpHeight,
                viewLeft        = $w.scrollLeft(),
                viewRight       = viewLeft + vpWidth,
                offset          = $t.offset(),
                _top            = offset.top,
                _bottom         = _top + $t.height(),
                _left           = offset.left,
                _right          = _left + $t.width(),
                compareTop      = partial === true ? _bottom : _top,
                compareBottom   = partial === true ? _top : _bottom,
                compareLeft     = partial === true ? _right : _left,
                compareRight    = partial === true ? _left : _right;

            if(direction === 'both')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
            else if(direction === 'vertical')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
            else if(direction === 'horizontal')
                return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
        }
    };

})(jQuery);

$(function() {
    $(window).scroll(function() {
        $(".wrapper > header").visible(true) ?
            $(".wrapper > main > nav").removeClass("fixed") :
            $(".wrapper > main > nav").addClass("fixed");
    });
});

Here's an example that uses jquery-visible plugin: http://jsfiddle.net/711p4em4/.

HTML:

<div class = "wrapper">
    <header>Header</header>
    <main>
        <nav>Stick to top</nav>
        Content
    </main>
    <footer>Footer</footer>
</div>

CSS:

* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #e2e2e2;
}

.wrapper > header,
.wrapper > footer {
    font: 20px/2 Sans-Serif;
    text-align: center;
    background-color: #0040FF;
    color: #fff;
}

.wrapper > main {
    position: relative;
    height: 500px;
    background-color: #5e5e5e;
    font: 20px/500px Sans-Serif;
    color: #fff;
    text-align: center;
    padding-top: 40px;
}

.wrapper > main > nav {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    font: 20px/2 Sans-Serif;
    color: #fff;
    text-align: center;
    background-color: #FFBF00;
}

.wrapper > main > nav.fixed {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}

JS (include jquery-visible plugin):

(function($){

    /**
     * Copyright 2012, Digital Fusion
     * Licensed under the MIT license.
     * http://teamdf.com/jquery-plugins/license/
     *
     * @author Sam Sehnert
     * @desc A small plugin that checks whether elements are within
     *       the user visible viewport of a web browser.
     *       only accounts for vertical position, not horizontal.
     */
    var $w = $(window);
    $.fn.visible = function(partial,hidden,direction){

        if (this.length < 1)
            return;

        var $t        = this.length > 1 ? this.eq(0) : this,
            t         = $t.get(0),
            vpWidth   = $w.width(),
            vpHeight  = $w.height(),
            direction = (direction) ? direction : 'both',
            clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

        if (typeof t.getBoundingClientRect === 'function'){

            // Use this native browser method, if available.
            var rec = t.getBoundingClientRect(),
                tViz = rec.top    >= 0 && rec.top    <  vpHeight,
                bViz = rec.bottom >  0 && rec.bottom <= vpHeight,
                lViz = rec.left   >= 0 && rec.left   <  vpWidth,
                rViz = rec.right  >  0 && rec.right  <= vpWidth,
                vVisible   = partial ? tViz || bViz : tViz && bViz,
                hVisible   = partial ? lViz || rViz : lViz && rViz;

            if(direction === 'both')
                return clientSize && vVisible && hVisible;
            else if(direction === 'vertical')
                return clientSize && vVisible;
            else if(direction === 'horizontal')
                return clientSize && hVisible;
        } else {

            var viewTop         = $w.scrollTop(),
                viewBottom      = viewTop + vpHeight,
                viewLeft        = $w.scrollLeft(),
                viewRight       = viewLeft + vpWidth,
                offset          = $t.offset(),
                _top            = offset.top,
                _bottom         = _top + $t.height(),
                _left           = offset.left,
                _right          = _left + $t.width(),
                compareTop      = partial === true ? _bottom : _top,
                compareBottom   = partial === true ? _top : _bottom,
                compareLeft     = partial === true ? _right : _left,
                compareRight    = partial === true ? _left : _right;

            if(direction === 'both')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
            else if(direction === 'vertical')
                return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
            else if(direction === 'horizontal')
                return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
        }
    };

})(jQuery);

$(function() {
    $(window).scroll(function() {
        $(".wrapper > header").visible(true) ?
            $(".wrapper > main > nav").removeClass("fixed") :
            $(".wrapper > main > nav").addClass("fixed");
    });
});
小镇女孩 2024-08-06 01:55:49

我使用了上面的一些工作来创建这项技术。 我对其进行了一些改进,并认为我会分享我的工作。 希望这可以帮助。

jsfiddle 代码

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();​

这是一种更加动态的滚动方式。 它确实需要一些工作,我会在某个时候将其变成一个插件,但这是我经过一小时的工作后想到的。

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.

jsfiddle Code

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.

醉梦枕江山 2024-08-06 01:55:49

我有一个类似的问题 - 我有一个 div 已经浮动在由 CSS 定义的其他内容上方的“固定”位置。 我想要实现的是,当我向下滚动页面时,div 将开始向下滚动内容,但然后粘在页面顶部(即永远不会消失)。

我的 div 的样式是:

.inProjectNavigation {
  width: 60.5%;
  max-width: 1300px;
  position: fixed; top: 60%;
  display: block;
}

我简单地将这个 div 放在页面上的某个位置,它出现在内容的顶部。 对其父母的风格没有特殊要求。

使其粘在顶部的 JS 是:

const MIN_TOP_POSITION = 30;

/**
 * Make the project navigation initially scroll down with the page, but then stick to the top of the browser
 */
$(window).scroll(function(e){ 
  let $navigationDiv = $('.inProjectNavigation');
  let originalTopPosPx = $navigationDiv.attr('data-originalTopPosPx');
  //-- on first scroll, save the original px position in the element, as defined by CSS
  if (originalTopPosPx == null) {
    let cssValue = $navigationDiv.css('top');
    originalTopPosPx = cssValue.substring(0, cssValue.length - 2); // get rid of the 'px'
    $navigationDiv.attr('data-originalTopPosPx', originalTopPosPx); 
  }
  //-- follow the scroll, but stick to top
  $navigationDiv.css({'top': Math.max(MIN_TOP_POSITION, (originalTopPosPx - $(this).scrollTop())) + 'px'});
});

在 Mac 上测试 - Safari、Firefox、Chrome。 希望 IE 也能工作:)

I had a similar problem - I had a div that was already floating in 'fixed' position above other content, defined by CSS. What I wanted to achieve was when I scrolled the page down, the div would start scrolling down with content but then stick to the top of the page (i.e. would never disappear).

The style of my div is:

.inProjectNavigation {
  width: 60.5%;
  max-width: 1300px;
  position: fixed; top: 60%;
  display: block;
}

I simply put this div somewhere on the page and it appears on top of content. There are no special requirements for the style of its parents.

The the JS to make it stick to the top is:

const MIN_TOP_POSITION = 30;

/**
 * Make the project navigation initially scroll down with the page, but then stick to the top of the browser
 */
$(window).scroll(function(e){ 
  let $navigationDiv = $('.inProjectNavigation');
  let originalTopPosPx = $navigationDiv.attr('data-originalTopPosPx');
  //-- on first scroll, save the original px position in the element, as defined by CSS
  if (originalTopPosPx == null) {
    let cssValue = $navigationDiv.css('top');
    originalTopPosPx = cssValue.substring(0, cssValue.length - 2); // get rid of the 'px'
    $navigationDiv.attr('data-originalTopPosPx', originalTopPosPx); 
  }
  //-- follow the scroll, but stick to top
  $navigationDiv.css({'top': Math.max(MIN_TOP_POSITION, (originalTopPosPx - $(this).scrollTop())) + 'px'});
});

Tested on a Mac - Safari, Firefox, Chrome. Hopefully should work in IE too :)

嘿咻 2024-08-06 01:55:49

要将任何内容粘贴到屏幕顶部,position:sticky; 将不起作用。 我在使用侧边栏时遇到了同样的情况,并且我能够使用 position:fixed; 将其固定。

这是我的整个网站:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html><head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="UTF-8">
        <title>Events Beta</title>
        <style>
          /* COMMON */
body {
    font-family: 'Segoe UI', sans-serif;
    margin: 0px;
    width: 100%;
    height: 100%;
}
a, button {
    margin: 8px;
    padding: 10px;
    border-radius: 8px;
    background-color: #0d6efd;
    border: 1px solid #fff;
    color: #fff;
    text-decoration: none;
    transition: background-color 0.9s;
    display: inline-flex;
}
.secondary {
    background-color: #ffffff00;
    color: #ccc;
    float: right;
    border: 2px solid #ccc;
}
a:hover, button:hover {
    background-color: #5398fe;
}
h1, h2, h3 {
    font-weight: 600;
}
dialog {
    border-radius: 6px;
}
header {
    background-color: #212020;
    margin: 0px; 
    padding: 15px; 
    color: #ffffff;
    height: 32px;
}
header img {
    width: auto;
    height: 32px;
}
select {
    padding: 10px;
    border-radius: 5px;
    background-color: rgb(248, 249, 250);;
    color: rgb(33, 37, 41);
}
.object {
    background-color: #ccc;
    border-radius: 6px;
    padding: 8px;
    margin: 8px;
    width: 40%;
    display: inline-block;
    vertical-align: top;
}
input, textarea {
    padding: 10px;
    border: 1px solid rgb(222, 226, 230);
    background-color: rgb(248, 249, 250);
    color: rgb(33, 37, 41);
    border-radius: 5px;
}
footer {
    padding: 15px;
    background-color: rgb(248, 249, 250);
    color: #0d6efd;
}
footer a {
    color: inherit;
    text-decoration: none;
    background-color: #ffffff00;
    border: none;

}
a.secondary {
    float: right;
    background-color: #ffffff00;
    color: #000;
}
.clear {
    clear: both;
}
.island {
    text-align: center;
    border: 2px solid #ccc;
    width: fit-content;
    border-radius: 6px;
    margin: auto;
    padding: 10px;
    margin-top: 10px;
}
.exclusive {
    display: none;
}
/* NAV */
.top_menu nav {
    float: right;
}
.top_menu nav a {
    font-weight: 600;
    padding-left: 20px;
    color: #ffffff;
    text-decoration: none;
    background-color: #ffffff00;
    border: none;
    display: inline;
}
.top_menu nav a:first-child {
    padding-left: 0px;
}

/* FORM COMMON */
.form-inline {
    margin: 15px 0px;
    max-width: 330px;
    background-color: #f5f5f5;
    border-radius: 5px;
    padding: 15px;
}
.form-inline label {
    width: 100px;
    display: block;
    float: left;
    margin-top: 10px;
}
.form-inline input, 
.form-inline textarea, 
.form-inline select {
    margin-bottom: 5px;
    width: 200px;
}
.form-inline input[type="checkbox"] {
    margin-top: 15px;
}
.form-inline input::after, 
.form-inline textarea::after, 
.form-inline select::after,
.form-inline input[type="checkbox"]::after {
    content: " ";
    clear: both;
}

/* BLOG */
.blog-post {
    padding: 15px 0px 18px 0px;
    border-bottom: 2px dotted #ccc;
    clear: both;
}
.blog-post:last-child {
    border-bottom: 0px;
}
.blog-date {
    float: right;
    color: #9f9f9f;
}
.blog-post h3.blog-title {
    margin: 0px 0px 10px 0px;
    padding: 5px 10px;
    background-color: #7250ef;
    color: #fff;
    display: inline-block;
    border-radius: 3px;
}
.blog-categories {
    font-weight: 600;
    color: #adabf4;
    font-size: 14px;
    padding-top: 10px;
}
.blog-content {
    font-size: 17px;
}
.container

/* EVENTS */
.inline-text {
    width: 300px;
}

/* Sidebar CSS */


html, body {
    height: 100%;

    }
    body {
    margin: 0;
    padding: 0;
    }
    /* Let's style our sidebar */
    .sidebar {
    width: 30%;
    background-color: #333;
    color: white;
    position: absolute;
    overflow-x: hidden;
    overflow-y: auto;
    height: 100%;
    }
    .sidebar > div {
    padding: 1px 20px 20px 20px;
    }
    .sidebar ul {
    padding-left: 0px;
    }
    .sidebar li {
    list-style-type: none;
    }
    .sidebar li a {
    color: inherit;
    text-decoration: none;
    border-radius: 4px;
    padding: 8px;
    margin: 0px -8px;
    display: block;
    background-color: #ffffff00;
    }
    .sidebar li a.active,
    .sidebar li a.active:hover {
    background-color: #666;
    }
    .sidebar li a:hover {
    background-color: #444;
    }
    /* Some styling for the main content area */
    .container { 
        margin-left: 250px;    /* Leave space for the sidebar */
        overflow-x: hidden;
        overflow-y: auto;
        height: 80%;
        width: 70%;
    }
    .container .page {
        padding: 20px;
        height: 100%;
        display: none;
        padding-bottom: 0px;
        padding-right: 0px;

    }
    .container .page.display {
        display: block;
    }


/* Media Queries */
@media (max-width: 700px) {
    .container {
        margin-left: 0px !important;
        width: 100% !important;
    }
    .sidebar {
        float: none !important;
        text-align: center !important;
        height: fit-content !important;
        width: 100% !important;
        position: sticky !important;
        top: 0px;
    }
    .sidebar a {
        width: fit-content;
    }
    #mobile-nav {
        display: inline;
    }
    #desk-nav {
        display: none;
    }
    .object {
        width: 90%;
    }
}
@media (min-width: 700px) {
    .sidebar {
        width: 230px !important;
        padding: 15px;
    }
    #desk-nav {
        display: inline;
    }
    #mobile-nav {
        display: none;
    }
} 

        </style>
        <link rel="icon" href="logo_white.png" type="image/png">
        <script src="script.js"></script>
        <script>
            function auth() {
                var good = document.cookie.indexOf('authToken');
                var createButton = document.querySelector("button#create_event.exclusive");
                if (good = true) {
                    document.querySelector("button#create_event.exclusive").style.display = "inline-flex";
                    
                }
                function redirect() {
                    createButton.addEventListener('click', redirect);
                }
            }
            var head = document.querySelector("header.top_menu");
            var body = document.querySelector("div.container");
            body.width = head.width;
            
            
            
            
            auth();
        </script>
    </head>
    <body>
        <header class="top_menu">
            <img id="logo" src="logo_white.png">
            <nav>
                <button onclick="talDialogOpen()">Projects</button>
                <dialog id="tal">
                    <button onclick="talDialogClose()" class="secondary">Close</button>
                    <h3>Projects</h3>
                    <small>This is a list of my projects. You can see my GitHub for more.</small>
                    <div class="object">
                        <h3>The Agent: Legacy</h3>
                        <p>A game about how an FBI agent uncovers a scheme to steal the plans for a military drug that is much bigger than himself
                        <br>
                        This game is being made in Unreal Engine 5.2, but may be moved to CryENGINE due to fees.
                        <br>
                        Platforms: Mainly PC but all</p>
                    </div>
                </dialog>
                <dialog id="events">
                    <button onclick="evDialogClose()" class="secondary">Close</button>
                    <h3>Events</h3>
                    <div class="object">
                        There are no events right now.
                    </div>
                    <a href="events.php"><button class="exclusive" id="create_event">Create Event</button></a>
                </dialog>

                <button onclick="evDialogOpen()">Events</button>

                <script>
                    function evDialogOpen() {
                        document.getElementById("events").open = true;
                    }
                    function evDialogClose() {
                        document.getElementById("events").close();
                    }
                </script>
                <script>
                    // Script to handle dialogs
                    function talDialogOpen() {
                        document.getElementById("tal").open = true;
                    }
                    function talDialogClose() {
                        document.getElementById("tal").close();
                    }
                </script>
            </nav>
                <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
                <script>
                    
                    // define a default navigation starting point (usually first link on sidebar nav)
                    var default_nav_hash = "#home";
                    
                    // handle sidebar navigation hash for "initial load of page"
                    function nav_hash() {
                    
                    // make sure its a string and the length is larger than a '#' value
                    if (window.location.hash.length <= 1) {
                        // set the default hash in the URL
                        window.location.hash = default_nav_hash;
                    }

                    // set it as .active (default was set above if there was none)
                    $('.sidebar a[href="' + window.location.hash + '"]').addClass('active');
                    $('#' + window.location.hash.substring(1) + '.page').addClass('display');

                    }

                    // once the document is ready (DOM - Document Object Model)
                    $(document).ready(function() {

                    // process initial load of page
                    nav_hash();
                    
                    // process based on click
                    $('.sidebar a').click(function() {
                        
                        // clear .active from all
                        $('.sidebar a').removeClass('active');
                        $('.page').removeClass('display');
                        
                        // set THIS to active (its been clicked on)
                        $(this).addClass('active');
                        $('#' + $(this).attr('href').substring(1) + '.page').addClass('display');

                    });

                    });

                </script>
                <style>
                    html, body {
                    height: 100%;

                    }
                    body {
                    margin: 0;
                    padding: 0;
                    }
                    /* Let's style our sidebar */
                    .sidebar {
                    width: 30%;
                    background-color: #333;
                    color: white;
                    position: absolute;
                    overflow-x: hidden;
                    overflow-y: auto;
                    height: 100%;
                    }
                    .sidebar > div {
                    padding: 1px 20px 20px 20px;
                    }
                    .sidebar ul {
                    padding-left: 0px;
                    }
                    .sidebar li {
                    list-style-type: none;
                    }
                    .sidebar li a {
                    color: inherit;
                    text-decoration: none;
                    border-radius: 4px;
                    padding: 8px;
                    margin: 0px -8px;
                    display: block;
                    }
                    .sidebar li a.active,
                    .sidebar li a.active:hover {
                    background-color: #666;
                    }
                    .sidebar li a:hover {
                    background-color: #444;
                    }
                    /* Some styling for the main content area */
                    .container { 
                        margin-left: 250px;    /* Leave space for the sidebar */
                        overflow-x: hidden;
                        overflow-y: auto;
                        height: 100%;
                        width: 70%;
                    }
                    .container .page {
                        padding: 20px;
                        height: 100%;
                        display: none; /* treat as page pages */

                    }
                    .container .page.display {
                        display: block;
                    }
                </style>
                
                

                <!-- Sidebar -->
                
            
        </header>
        <section>

<nav>
    <div class="sidebar">
        <div id="mobile-nav">
            <a href="#home">Home</a>
            <a href="#portfolio">Info</a>
            <a href="#contact">FBLA</a>
            <a href="#classes">Schedule</a>
            <a href="#guides" class="active">Events</a>
        </div>
        <div id="desk-nav">
            <h2>Pages</h2>
            <li><a href="#home">Home</a></li>
            <li><a href="#portfolio">Info</a></li>
            <li><a href="#contact">FBLA</a></li>
            <li><a href="#classes">Schedule</a></li>
            <li><a href="#guides" class="active">Events</a></li>
        </div>
    </div>
</nav>

  <!-- Each Div element in here counts as a section that won't display unless it is selected on the sidebar. The code in in header.php -->
  <div class="container">
    
    <div class="page" id="home">
        <h1>Hello, User!</h1>
        <p>
            Welcome to the website for Events Beta! This will be used for purposes like sharing info. 
            <br>
            Visit the other tabs on the left (or top if your on a phone), and explore.
            <br>
            Here is an app list so you can go places fast:
            </p><ul>
                <li><a href="https://mail.google.com" target="_blank">Gmail</a></li>
                <li><a href="https://mail.google.com/chat" target="_blank">Google Chat</a></li>
                <li><a href="https://www.github.com/realitygamesdev" target="_blank">GitHub</a></li>
                <li><a href="mailto:****************@gmail.com" target="_blank">Email me</a><small>This may not work, as the browser cannot open emails and you need to have an email client like Outlook installed on your device.</small></li>
            </ul>
        <p></p>
    </div>

    <div class="page" id="portfolio">
        <h1>Info</h1>
        <p>This is my and any mutual info that should be listed on this website.</p>
        <ul>
            <li>School: Osceola Creek Middle School</li>
            <li>Email: *******************@gmail.com <a href="https://mail.google.com">Open Gmail</a></li>
            <li>To chat with me and my friends, go to <a href="https://chat.google.com">Google Chat</a> and enter my email.</li>
        </ul>
        <p>You may also need my interests. Here they are.</p>
        <ul>
            <li>Coding</li>
            <li>Making Video Games</li>
            <li>Playing Video Games</li>
            <li>Working with media (videos, images, etc.)</li>
            <li>Anything on the computer</li>
        </ul>
    </div>

    <div class="page" id="classes">
        <h1>Classes</h1>
        <p>These are my daily classes in school, and their info.</p>
        <p>My daily periods</p>
        <>
            
        </>
    </div>

    <div class="page" id="contact">
        <h1>FBLA Projects</h1>
        <p>I am in FBLA, and have competitions all the time. The projects for them are in here.</p>
        <div class="object">
            <h2>Video Game Challenge</h2>
            <p>
                The challenge for this is to make a semi complicated video game to present to the judges.
                <br>
                The game is planned to be 3D, but may be 2D due to a lack of avalible resources. 
                <br>
                If it's 3D, it will be made in CryENGINE due to fees with Unreal Engine.
            </p>
        </div>
    </div>

        <div class="page display" id="guides">
            <h2>Events</h2>
            <p>Welcome to Events Beta. This is your console for seeing and participating in events.</p>

            <div class="object">
                <h3>Events</h3>
                <p>This module is in PHP</p>

    
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Loading</title>
        <script>
            
        </script>
    
    
        <div style="text-align: center;">
            <video src="loading.mp4" loop="" autoplay="" muted="" width="50px"></video>
            <noscript>
                <div style="background-color: red;color:white;width:fit-content;border-radius:6px;padding:10px;margin-left:40%;">
                    This site uses JavaScript to function correctly.
                    <br>
                    You would normally see content here, but you must enable JavaScript first.
                </div>
            </noscript>
        </div>
    
                <h3>Event: Chat with Caleb</h3><p>Date: 10/20/2023</p><p>Participants: Gabriel, Caleb</p><h3>Event: </h3><p>Date: </p><p>Participants: </p>            </div>


            <div class="object">
                <h3>Add an event</h3>
                <p>Use the form below to add an event that others can participate in.</p>
                <form action="api.php" method="post">
                <label for="event_name">Event Name:</label>
                <input type="text" id="event_name" name="event_name" required="">
                <br>
                <label for="event_date">Event Date:</label>
                <input type="date" id="event_date" name="event_date" required="">
                <br>
                <label for="event_participants">Participants (comma-separated):</label>
                <input type="text" id="event_participants" name="event_participants">
                <br>
                <button type="submit">Add Event</button>
                </form>
            </div>

            <h2>Developers</h2>
            <p>This section is for developers (or me) who want to use my API.</p>

            <div class="object">
                <h3>Import the API</h3>
                <p>To import the API, link https://gabriel.jemail.us/api.js</p>
                <p>This is a JavaScript API. <b>It is not compatible with Python.</b></p>
            </div>

            <div class="object">
                <h3>API Reference</h3>
                <p>
                To see documentation for the API, click the button.
                <a href="docs.txt" download="">See docs</a>
                </p>
            </div>
            </div>
        
    </div>

  






</section>



    </body></html>

如果您的屏幕小于 700PX,导航栏将不会粘住。 不要打开对话框,因为它正在开发

这是我网站的代码。 它在 Chrome 中运行良好,但请测试一下。 这是我的解决方案,对其他人来说应该没问题。

To stick anything to the top of the screen, position: sticky; won't work. I am experiencing the same situation with a sidebar, and I was able to stick it with position: fixed;.

Here is my whole website:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html><head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="UTF-8">
        <title>Events Beta</title>
        <style>
          /* COMMON */
body {
    font-family: 'Segoe UI', sans-serif;
    margin: 0px;
    width: 100%;
    height: 100%;
}
a, button {
    margin: 8px;
    padding: 10px;
    border-radius: 8px;
    background-color: #0d6efd;
    border: 1px solid #fff;
    color: #fff;
    text-decoration: none;
    transition: background-color 0.9s;
    display: inline-flex;
}
.secondary {
    background-color: #ffffff00;
    color: #ccc;
    float: right;
    border: 2px solid #ccc;
}
a:hover, button:hover {
    background-color: #5398fe;
}
h1, h2, h3 {
    font-weight: 600;
}
dialog {
    border-radius: 6px;
}
header {
    background-color: #212020;
    margin: 0px; 
    padding: 15px; 
    color: #ffffff;
    height: 32px;
}
header img {
    width: auto;
    height: 32px;
}
select {
    padding: 10px;
    border-radius: 5px;
    background-color: rgb(248, 249, 250);;
    color: rgb(33, 37, 41);
}
.object {
    background-color: #ccc;
    border-radius: 6px;
    padding: 8px;
    margin: 8px;
    width: 40%;
    display: inline-block;
    vertical-align: top;
}
input, textarea {
    padding: 10px;
    border: 1px solid rgb(222, 226, 230);
    background-color: rgb(248, 249, 250);
    color: rgb(33, 37, 41);
    border-radius: 5px;
}
footer {
    padding: 15px;
    background-color: rgb(248, 249, 250);
    color: #0d6efd;
}
footer a {
    color: inherit;
    text-decoration: none;
    background-color: #ffffff00;
    border: none;

}
a.secondary {
    float: right;
    background-color: #ffffff00;
    color: #000;
}
.clear {
    clear: both;
}
.island {
    text-align: center;
    border: 2px solid #ccc;
    width: fit-content;
    border-radius: 6px;
    margin: auto;
    padding: 10px;
    margin-top: 10px;
}
.exclusive {
    display: none;
}
/* NAV */
.top_menu nav {
    float: right;
}
.top_menu nav a {
    font-weight: 600;
    padding-left: 20px;
    color: #ffffff;
    text-decoration: none;
    background-color: #ffffff00;
    border: none;
    display: inline;
}
.top_menu nav a:first-child {
    padding-left: 0px;
}

/* FORM COMMON */
.form-inline {
    margin: 15px 0px;
    max-width: 330px;
    background-color: #f5f5f5;
    border-radius: 5px;
    padding: 15px;
}
.form-inline label {
    width: 100px;
    display: block;
    float: left;
    margin-top: 10px;
}
.form-inline input, 
.form-inline textarea, 
.form-inline select {
    margin-bottom: 5px;
    width: 200px;
}
.form-inline input[type="checkbox"] {
    margin-top: 15px;
}
.form-inline input::after, 
.form-inline textarea::after, 
.form-inline select::after,
.form-inline input[type="checkbox"]::after {
    content: " ";
    clear: both;
}

/* BLOG */
.blog-post {
    padding: 15px 0px 18px 0px;
    border-bottom: 2px dotted #ccc;
    clear: both;
}
.blog-post:last-child {
    border-bottom: 0px;
}
.blog-date {
    float: right;
    color: #9f9f9f;
}
.blog-post h3.blog-title {
    margin: 0px 0px 10px 0px;
    padding: 5px 10px;
    background-color: #7250ef;
    color: #fff;
    display: inline-block;
    border-radius: 3px;
}
.blog-categories {
    font-weight: 600;
    color: #adabf4;
    font-size: 14px;
    padding-top: 10px;
}
.blog-content {
    font-size: 17px;
}
.container

/* EVENTS */
.inline-text {
    width: 300px;
}

/* Sidebar CSS */


html, body {
    height: 100%;

    }
    body {
    margin: 0;
    padding: 0;
    }
    /* Let's style our sidebar */
    .sidebar {
    width: 30%;
    background-color: #333;
    color: white;
    position: absolute;
    overflow-x: hidden;
    overflow-y: auto;
    height: 100%;
    }
    .sidebar > div {
    padding: 1px 20px 20px 20px;
    }
    .sidebar ul {
    padding-left: 0px;
    }
    .sidebar li {
    list-style-type: none;
    }
    .sidebar li a {
    color: inherit;
    text-decoration: none;
    border-radius: 4px;
    padding: 8px;
    margin: 0px -8px;
    display: block;
    background-color: #ffffff00;
    }
    .sidebar li a.active,
    .sidebar li a.active:hover {
    background-color: #666;
    }
    .sidebar li a:hover {
    background-color: #444;
    }
    /* Some styling for the main content area */
    .container { 
        margin-left: 250px;    /* Leave space for the sidebar */
        overflow-x: hidden;
        overflow-y: auto;
        height: 80%;
        width: 70%;
    }
    .container .page {
        padding: 20px;
        height: 100%;
        display: none;
        padding-bottom: 0px;
        padding-right: 0px;

    }
    .container .page.display {
        display: block;
    }


/* Media Queries */
@media (max-width: 700px) {
    .container {
        margin-left: 0px !important;
        width: 100% !important;
    }
    .sidebar {
        float: none !important;
        text-align: center !important;
        height: fit-content !important;
        width: 100% !important;
        position: sticky !important;
        top: 0px;
    }
    .sidebar a {
        width: fit-content;
    }
    #mobile-nav {
        display: inline;
    }
    #desk-nav {
        display: none;
    }
    .object {
        width: 90%;
    }
}
@media (min-width: 700px) {
    .sidebar {
        width: 230px !important;
        padding: 15px;
    }
    #desk-nav {
        display: inline;
    }
    #mobile-nav {
        display: none;
    }
} 

        </style>
        <link rel="icon" href="logo_white.png" type="image/png">
        <script src="script.js"></script>
        <script>
            function auth() {
                var good = document.cookie.indexOf('authToken');
                var createButton = document.querySelector("button#create_event.exclusive");
                if (good = true) {
                    document.querySelector("button#create_event.exclusive").style.display = "inline-flex";
                    
                }
                function redirect() {
                    createButton.addEventListener('click', redirect);
                }
            }
            var head = document.querySelector("header.top_menu");
            var body = document.querySelector("div.container");
            body.width = head.width;
            
            
            
            
            auth();
        </script>
    </head>
    <body>
        <header class="top_menu">
            <img id="logo" src="logo_white.png">
            <nav>
                <button onclick="talDialogOpen()">Projects</button>
                <dialog id="tal">
                    <button onclick="talDialogClose()" class="secondary">Close</button>
                    <h3>Projects</h3>
                    <small>This is a list of my projects. You can see my GitHub for more.</small>
                    <div class="object">
                        <h3>The Agent: Legacy</h3>
                        <p>A game about how an FBI agent uncovers a scheme to steal the plans for a military drug that is much bigger than himself
                        <br>
                        This game is being made in Unreal Engine 5.2, but may be moved to CryENGINE due to fees.
                        <br>
                        Platforms: Mainly PC but all</p>
                    </div>
                </dialog>
                <dialog id="events">
                    <button onclick="evDialogClose()" class="secondary">Close</button>
                    <h3>Events</h3>
                    <div class="object">
                        There are no events right now.
                    </div>
                    <a href="events.php"><button class="exclusive" id="create_event">Create Event</button></a>
                </dialog>

                <button onclick="evDialogOpen()">Events</button>

                <script>
                    function evDialogOpen() {
                        document.getElementById("events").open = true;
                    }
                    function evDialogClose() {
                        document.getElementById("events").close();
                    }
                </script>
                <script>
                    // Script to handle dialogs
                    function talDialogOpen() {
                        document.getElementById("tal").open = true;
                    }
                    function talDialogClose() {
                        document.getElementById("tal").close();
                    }
                </script>
            </nav>
                <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
                <script>
                    
                    // define a default navigation starting point (usually first link on sidebar nav)
                    var default_nav_hash = "#home";
                    
                    // handle sidebar navigation hash for "initial load of page"
                    function nav_hash() {
                    
                    // make sure its a string and the length is larger than a '#' value
                    if (window.location.hash.length <= 1) {
                        // set the default hash in the URL
                        window.location.hash = default_nav_hash;
                    }

                    // set it as .active (default was set above if there was none)
                    $('.sidebar a[href="' + window.location.hash + '"]').addClass('active');
                    $('#' + window.location.hash.substring(1) + '.page').addClass('display');

                    }

                    // once the document is ready (DOM - Document Object Model)
                    $(document).ready(function() {

                    // process initial load of page
                    nav_hash();
                    
                    // process based on click
                    $('.sidebar a').click(function() {
                        
                        // clear .active from all
                        $('.sidebar a').removeClass('active');
                        $('.page').removeClass('display');
                        
                        // set THIS to active (its been clicked on)
                        $(this).addClass('active');
                        $('#' + $(this).attr('href').substring(1) + '.page').addClass('display');

                    });

                    });

                </script>
                <style>
                    html, body {
                    height: 100%;

                    }
                    body {
                    margin: 0;
                    padding: 0;
                    }
                    /* Let's style our sidebar */
                    .sidebar {
                    width: 30%;
                    background-color: #333;
                    color: white;
                    position: absolute;
                    overflow-x: hidden;
                    overflow-y: auto;
                    height: 100%;
                    }
                    .sidebar > div {
                    padding: 1px 20px 20px 20px;
                    }
                    .sidebar ul {
                    padding-left: 0px;
                    }
                    .sidebar li {
                    list-style-type: none;
                    }
                    .sidebar li a {
                    color: inherit;
                    text-decoration: none;
                    border-radius: 4px;
                    padding: 8px;
                    margin: 0px -8px;
                    display: block;
                    }
                    .sidebar li a.active,
                    .sidebar li a.active:hover {
                    background-color: #666;
                    }
                    .sidebar li a:hover {
                    background-color: #444;
                    }
                    /* Some styling for the main content area */
                    .container { 
                        margin-left: 250px;    /* Leave space for the sidebar */
                        overflow-x: hidden;
                        overflow-y: auto;
                        height: 100%;
                        width: 70%;
                    }
                    .container .page {
                        padding: 20px;
                        height: 100%;
                        display: none; /* treat as page pages */

                    }
                    .container .page.display {
                        display: block;
                    }
                </style>
                
                

                <!-- Sidebar -->
                
            
        </header>
        <section>

<nav>
    <div class="sidebar">
        <div id="mobile-nav">
            <a href="#home">Home</a>
            <a href="#portfolio">Info</a>
            <a href="#contact">FBLA</a>
            <a href="#classes">Schedule</a>
            <a href="#guides" class="active">Events</a>
        </div>
        <div id="desk-nav">
            <h2>Pages</h2>
            <li><a href="#home">Home</a></li>
            <li><a href="#portfolio">Info</a></li>
            <li><a href="#contact">FBLA</a></li>
            <li><a href="#classes">Schedule</a></li>
            <li><a href="#guides" class="active">Events</a></li>
        </div>
    </div>
</nav>

  <!-- Each Div element in here counts as a section that won't display unless it is selected on the sidebar. The code in in header.php -->
  <div class="container">
    
    <div class="page" id="home">
        <h1>Hello, User!</h1>
        <p>
            Welcome to the website for Events Beta! This will be used for purposes like sharing info. 
            <br>
            Visit the other tabs on the left (or top if your on a phone), and explore.
            <br>
            Here is an app list so you can go places fast:
            </p><ul>
                <li><a href="https://mail.google.com" target="_blank">Gmail</a></li>
                <li><a href="https://mail.google.com/chat" target="_blank">Google Chat</a></li>
                <li><a href="https://www.github.com/realitygamesdev" target="_blank">GitHub</a></li>
                <li><a href="mailto:****************@gmail.com" target="_blank">Email me</a><small>This may not work, as the browser cannot open emails and you need to have an email client like Outlook installed on your device.</small></li>
            </ul>
        <p></p>
    </div>

    <div class="page" id="portfolio">
        <h1>Info</h1>
        <p>This is my and any mutual info that should be listed on this website.</p>
        <ul>
            <li>School: Osceola Creek Middle School</li>
            <li>Email: *******************@gmail.com <a href="https://mail.google.com">Open Gmail</a></li>
            <li>To chat with me and my friends, go to <a href="https://chat.google.com">Google Chat</a> and enter my email.</li>
        </ul>
        <p>You may also need my interests. Here they are.</p>
        <ul>
            <li>Coding</li>
            <li>Making Video Games</li>
            <li>Playing Video Games</li>
            <li>Working with media (videos, images, etc.)</li>
            <li>Anything on the computer</li>
        </ul>
    </div>

    <div class="page" id="classes">
        <h1>Classes</h1>
        <p>These are my daily classes in school, and their info.</p>
        <p>My daily periods</p>
        <>
            
        </>
    </div>

    <div class="page" id="contact">
        <h1>FBLA Projects</h1>
        <p>I am in FBLA, and have competitions all the time. The projects for them are in here.</p>
        <div class="object">
            <h2>Video Game Challenge</h2>
            <p>
                The challenge for this is to make a semi complicated video game to present to the judges.
                <br>
                The game is planned to be 3D, but may be 2D due to a lack of avalible resources. 
                <br>
                If it's 3D, it will be made in CryENGINE due to fees with Unreal Engine.
            </p>
        </div>
    </div>

        <div class="page display" id="guides">
            <h2>Events</h2>
            <p>Welcome to Events Beta. This is your console for seeing and participating in events.</p>

            <div class="object">
                <h3>Events</h3>
                <p>This module is in PHP</p>

    
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Loading</title>
        <script>
            
        </script>
    
    
        <div style="text-align: center;">
            <video src="loading.mp4" loop="" autoplay="" muted="" width="50px"></video>
            <noscript>
                <div style="background-color: red;color:white;width:fit-content;border-radius:6px;padding:10px;margin-left:40%;">
                    This site uses JavaScript to function correctly.
                    <br>
                    You would normally see content here, but you must enable JavaScript first.
                </div>
            </noscript>
        </div>
    
                <h3>Event: Chat with Caleb</h3><p>Date: 10/20/2023</p><p>Participants: Gabriel, Caleb</p><h3>Event: </h3><p>Date: </p><p>Participants: </p>            </div>


            <div class="object">
                <h3>Add an event</h3>
                <p>Use the form below to add an event that others can participate in.</p>
                <form action="api.php" method="post">
                <label for="event_name">Event Name:</label>
                <input type="text" id="event_name" name="event_name" required="">
                <br>
                <label for="event_date">Event Date:</label>
                <input type="date" id="event_date" name="event_date" required="">
                <br>
                <label for="event_participants">Participants (comma-separated):</label>
                <input type="text" id="event_participants" name="event_participants">
                <br>
                <button type="submit">Add Event</button>
                </form>
            </div>

            <h2>Developers</h2>
            <p>This section is for developers (or me) who want to use my API.</p>

            <div class="object">
                <h3>Import the API</h3>
                <p>To import the API, link https://gabriel.jemail.us/api.js</p>
                <p>This is a JavaScript API. <b>It is not compatible with Python.</b></p>
            </div>

            <div class="object">
                <h3>API Reference</h3>
                <p>
                To see documentation for the API, click the button.
                <a href="docs.txt" download="">See docs</a>
                </p>
            </div>
            </div>
        
    </div>

  






</section>



    </body></html>

IF YOUR SCREEN IN SMALLER THAN 700PX, THE NAVBAR WILL NOT STICK. DO NOT OPEN DIALOGS, AS THAT IS UNDER DEVELOPMENT

That is the code for my website. It works in Chrome fine, but please test it. This was my solution, it should be fine for others.

左秋 2024-08-06 01:55:48

这是没有 jquery 的方法(更新:查看其他答案,您现在可以仅使用 CSS 来做到这一点)

var startProductBarPos=-1;
window.onscroll=function(){
  var bar = document.getElementById('nav');
  if(startProductBarPos<0)startProductBarPos=findPosY(bar);

  if(pageYOffset>startProductBarPos){
    bar.style.position='fixed';
    bar.style.top=0;
  }else{
    bar.style.position='relative';
  }

};

function findPosY(obj) {
  var curtop = 0;
  if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
    curtop += obj.offsetTop;
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}
* {margin:0;padding:0;}
.nav {
  border: 1px red dashed;
  background: #00ffff;
  text-align:center;
  padding: 21px 0;

  margin: 0 auto;
  z-index:10; 
  width:100%;
  left:0;
  right:0;
}

.header {
  text-align:center;
  padding: 65px 0;
  border: 1px red dashed;
}

.content {
  padding: 500px 0;
  text-align:center;
  border: 1px red dashed;
}
.footer {
  padding: 100px 0;
  text-align:center;
  background: #777;
  border: 1px red dashed;
}
<header class="header">This is a Header</header>
<div id="nav" class="nav">Main Navigation</div>
<div class="content">Hello World!</div>
<footer class="footer">This is a Footer</footer>

And here's how without jquery (UPDATE: see other answers where you can now do this with CSS only)

var startProductBarPos=-1;
window.onscroll=function(){
  var bar = document.getElementById('nav');
  if(startProductBarPos<0)startProductBarPos=findPosY(bar);

  if(pageYOffset>startProductBarPos){
    bar.style.position='fixed';
    bar.style.top=0;
  }else{
    bar.style.position='relative';
  }

};

function findPosY(obj) {
  var curtop = 0;
  if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
    curtop += obj.offsetTop;
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}
* {margin:0;padding:0;}
.nav {
  border: 1px red dashed;
  background: #00ffff;
  text-align:center;
  padding: 21px 0;

  margin: 0 auto;
  z-index:10; 
  width:100%;
  left:0;
  right:0;
}

.header {
  text-align:center;
  padding: 65px 0;
  border: 1px red dashed;
}

.content {
  padding: 500px 0;
  text-align:center;
  border: 1px red dashed;
}
.footer {
  padding: 100px 0;
  text-align:center;
  background: #777;
  border: 1px red dashed;
}
<header class="header">This is a Header</header>
<div id="nav" class="nav">Main Navigation</div>
<div class="content">Hello World!</div>
<footer class="footer">This is a Footer</footer>

夜声 2024-08-06 01:55:48

我遇到了和你一样的问题,最后制作了一个 jQuery 插件来解决它。 它实际上解决了人们在这里列出的所有问题,此外它还添加了一些可选功能。

选项

stickyPanelSettings = {
    // Use this to set the top margin of the detached panel.
    topPadding: 0,

    // This class is applied when the panel detaches.
    afterDetachCSSClass: "",

    // When set to true the space where the panel was is kept open.
    savePanelSpace: false,

    // Event fires when panel is detached
    // function(detachedPanel, panelSpacer){....}
    onDetached: null,

    // Event fires when panel is reattached
    // function(detachedPanel){....}
    onReAttached: null,

    // Set this using any valid jquery selector to 
    // set the parent of the sticky panel.
    // If set to null then the window object will be used.
    parentSelector: null
};

https://github.com/donnyv/sticky-panel

演示: http://htmlpreview.github.io/?https://github.com/donnyv/sticky-panel/blob/master/jquery.stickyPanel/Main.htm

I had the same problem as you and ended up making a jQuery plugin to take care of it. It actually solves all the problems people have listed here, plus it adds a couple of optional features too.

Options

stickyPanelSettings = {
    // Use this to set the top margin of the detached panel.
    topPadding: 0,

    // This class is applied when the panel detaches.
    afterDetachCSSClass: "",

    // When set to true the space where the panel was is kept open.
    savePanelSpace: false,

    // Event fires when panel is detached
    // function(detachedPanel, panelSpacer){....}
    onDetached: null,

    // Event fires when panel is reattached
    // function(detachedPanel){....}
    onReAttached: null,

    // Set this using any valid jquery selector to 
    // set the parent of the sticky panel.
    // If set to null then the window object will be used.
    parentSelector: null
};

https://github.com/donnyv/sticky-panel

demo: http://htmlpreview.github.io/?https://github.com/donnyv/sticky-panel/blob/master/jquery.stickyPanel/Main.htm

早茶月光 2024-08-06 01:55:48

您可以在不使用 javascript 的情况下使用:

.element_to_stick {
  position: sticky;
  top: 0px; // Top calculated from div Parent, not top screen !
}

在 Safari 中,您仍然需要使用位置:-webkit-sticky。

You can make it without using javascript by using :

.element_to_stick {
  position: sticky;
  top: 0px; // Top calculated from div Parent, not top screen !
}

In Safari you still need to use position: -webkit-sticky.

冰葑 2024-08-06 01:55:48

为回答其他问题而提供的信息可能对您有所帮助,埃文:

检查元素在滚动后是否可见

您基本上想要修改元素的样式,仅在验证 document.body.scrollTop 值等于或大于元素顶部后将其设置为固定。

The info provided to answer this other question may be of help to you, 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.

木緿 2024-08-06 01:55:48

您可以简单地使用 css,将元素定位为 固定

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

< strong>编辑:您应该拥有绝对位置的元素,一旦滚动偏移到达该元素,就应该将其更改为固定,并且顶部位置应设置为零。

您可以使用 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'}); 
  } 
});

当滚动偏移达到 200 时,该元素将到浏览器窗口的顶部,因为它是固定放置的。

You could use simply css, positioning your element as 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.

You can detect the top scroll offset of the document with the scrollTop function:

$(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.

长不大的小祸害 2024-08-06 01:55:48

您已在 Google 代码的问题页面上看到过此示例,并且 (最近)在 Stack Overflow 的编辑页面上。

当您向上滚动时,CMS 的答案不会恢复定位。 这是从 Stack Overflow 上无耻地窃取的代码:

function moveScroller() {
    var $anchor = $("#scroller-anchor");
    var $scroller = $('#scroller');

    var move = function() {
        var st = $(window).scrollTop();
        var ot = $anchor.offset().top;
        if(st > ot) {
            $scroller.css({
                position: "fixed",
                top: "0px"
            });
        } else {
            $scroller.css({
                position: "relative",
                top: ""
            });
        }
    };
    $(window).scroll(move);
    move();
}
<div id="sidebar" style="width:270px;"> 
  <div id="scroller-anchor"></div> 
  <div id="scroller" style="margin-top:10px; width:270px"> 
    Scroller Scroller Scroller
  </div>
</div>

<script type="text/javascript"> 
  $(function() {
    moveScroller();
  });
</script> 

以及一个简单的现场演示

一个新兴的、无脚本的替代方案是 position: Sticky,Chrome、Firefox 和 Safari 都支持它。 请参阅有关 HTML5Rocks 的文章演示,以及Mozilla 文档

You've seen this example on Google Code's issue page and (only recently) on Stack Overflow's edit page.

CMS's answer doesn't revert the positioning when you scroll back up. Here's the shamelessly stolen code from Stack Overflow:

function moveScroller() {
    var $anchor = $("#scroller-anchor");
    var $scroller = $('#scroller');

    var move = function() {
        var st = $(window).scrollTop();
        var ot = $anchor.offset().top;
        if(st > ot) {
            $scroller.css({
                position: "fixed",
                top: "0px"
            });
        } else {
            $scroller.css({
                position: "relative",
                top: ""
            });
        }
    };
    $(window).scroll(move);
    move();
}
<div id="sidebar" style="width:270px;"> 
  <div id="scroller-anchor"></div> 
  <div id="scroller" style="margin-top:10px; width:270px"> 
    Scroller Scroller Scroller
  </div>
</div>

<script type="text/javascript"> 
  $(function() {
    moveScroller();
  });
</script> 

And a simple live demo.

A nascent, script-free alternative is position: sticky, which is supported in Chrome, Firefox, and Safari. See the article on HTML5Rocks and demo, and Mozilla docs.

哀由 2024-08-06 01:55:48

自 2017 年 1 月 Chrome 56 发布以来,大多数常用浏览器都支持 CSS 中的 position: Sticky 属性。

#thing_to_stick {
  position: sticky;
  top: 0;
}

在 Firefox 和 Chrome 中对我有用。

在 Safari 中,您仍然需要使用 position: -webkit-sticky

Polyfills 可用于 Internet Explorer 和 Edge; https://github.com/wilddeer/stickyfill 似乎是一个不错的选择。

As of January 2017 and the release of Chrome 56, most browsers in common use support the position: sticky property in CSS.

#thing_to_stick {
  position: sticky;
  top: 0;
}

does the trick for me in Firefox and Chrome.

In Safari you still need to use position: -webkit-sticky.

Polyfills are available for Internet Explorer and Edge; https://github.com/wilddeer/stickyfill seems to be a good one.

ヤ经典坏疍 2024-08-06 01:55:48

最简单的解决方案(没有js):
演示

.container {
  position: relative;
}
.sticky-div {
    position: sticky;
    top: 0;
}
<div class="container">
  <h1>
    relative container & sticky div
  </h1>
  <div class="sticky-div"> this row is sticky</div>
  <div>
    content
  </div>
</div>

The simplest solution (without js) :
demo

.container {
  position: relative;
}
.sticky-div {
    position: sticky;
    top: 0;
}
<div class="container">
  <h1>
    relative container & sticky div
  </h1>
  <div class="sticky-div"> this row is sticky</div>
  <div>
    content
  </div>
</div>
云柯 2024-08-06 01:55:48

我的解决方案有点冗长,但它可以处理居中布局的左边缘的可变定位。

// 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));
    });
};

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));
    });
};
看春风乍起 2024-08-06 01:55:48

这是 Josh Lee 答案的扩展版本。 如果您希望 div 位于右侧边栏上,并在一定范围内浮动(即,您需要指定顶部和底部锚点位置)。 它还修复了您在移动设备上查看此内容时的错误(您需要检查左侧滚动位置,否则 div 将移出屏幕)。

function moveScroller() {
    var move = function() {
        var st = $(window).scrollTop();
        var sl = $(window).scrollLeft();
        var ot = $("#scroller-anchor-top").offset().top;
        var ol = $("#scroller-anchor-top").offset().left;
        var bt = $("#scroller-anchor-bottom").offset().top;
        var s = $("#scroller");
        if(st > ot) {
            if (st < bt - 280) //280px is the approx. height for the sticky div
            {
                s.css({
                    position: "fixed",
                    top: "0px",
                    left: ol-sl
                }); 
            }
            else
            {
                s.css({
                    position: "fixed",
                    top: bt-st-280,
                    left: ol-sl
                }); 
            }
        } else {
            s.css({
                position: "relative",
                top: "",
                left: ""
            });

        }
    };
    $(window).scroll(move);
    move();
}

Here is an extended version to Josh Lee's answer. If you want the div to be on sidebar to the right, and float within a range (i.e., you need to specify top and bottom anchor positions). It also fixes a bug when you view this on mobile devices (you need to check left scroll position otherwise the div will move off screen).

function moveScroller() {
    var move = function() {
        var st = $(window).scrollTop();
        var sl = $(window).scrollLeft();
        var ot = $("#scroller-anchor-top").offset().top;
        var ol = $("#scroller-anchor-top").offset().left;
        var bt = $("#scroller-anchor-bottom").offset().top;
        var s = $("#scroller");
        if(st > ot) {
            if (st < bt - 280) //280px is the approx. height for the sticky div
            {
                s.css({
                    position: "fixed",
                    top: "0px",
                    left: ol-sl
                }); 
            }
            else
            {
                s.css({
                    position: "fixed",
                    top: bt-st-280,
                    left: ol-sl
                }); 
            }
        } else {
            s.css({
                position: "relative",
                top: "",
                left: ""
            });

        }
    };
    $(window).scroll(move);
    move();
}
琴流音 2024-08-06 01:55:48

我在寻找同样的东西时遇到了这个。 我知道这是一个老问题,但我想我应该提供一个更新的答案。

Scrollorama 有一个“固定它”功能,这正是我所寻找的。

http://johnpolacek.github.io/scrollorama/

I came across this when searching for the same thing. I know it's an old question but I thought I'd offer a more recent answer.

Scrollorama has a 'pin it' feature which is just what I was looking for.

http://johnpolacek.github.io/scrollorama/

梦一生花开无言 2024-08-06 01:55:48

大多数常用的浏览器都支持CSS中的position:sticky属性。

div { 位置:-webkit-sticky; 位置:粘性; 顶部:0; }

most browsers in common use support the position: sticky property in CSS.

div { position: -webkit-sticky; position: sticky; top: 0; }

正如 Josh LeeColin 't Hart 说过,你可以选择只使用 position: Sticky; top: 0; 应用于您想要滚动的 div...

另外,您唯一要做的就是将其复制到页面顶部或将其格式化以适合外部 CSS 表:

<style>
#sticky_div's_name_here { position: sticky; top: 0; }
</style>

只需将 #sticky_div's_name_here 替换为您的 div 名称,即如果您的 div 是

您将输入 #示例 { 位置:粘性; 顶部:0; }

As Josh Lee and Colin 't Hart have said, you could optionally just use position: sticky; top: 0; applying to the div that you want the scrolling at...

Plus, the only thing you will have to do is copy this into the top of your page or format it to fit into an external CSS sheet:

<style>
#sticky_div's_name_here { position: sticky; top: 0; }
</style>

Just replace #sticky_div's_name_here with the name of your div, i.e. if your div was <div id="example"> you would put #example { position: sticky; top: 0; }.

等待我真够勒 2024-08-06 01:55:48

这是另一个选项:

JAVASCRIPT

var initTopPosition= $('#myElementToStick').offset().top;   
$(window).scroll(function(){
    if($(window).scrollTop() > initTopPosition)
        $('#myElementToStick').css({'position':'fixed','top':'0px'});
    else
        $('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});

您的 #myElementToStick 应该以 position:absolute CSS 属性开头。

Here is another option:

JAVASCRIPT

var initTopPosition= $('#myElementToStick').offset().top;   
$(window).scroll(function(){
    if($(window).scrollTop() > initTopPosition)
        $('#myElementToStick').css({'position':'fixed','top':'0px'});
    else
        $('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});

Your #myElementToStick should start with position:absolute CSS property.

风启觞 2024-08-06 01:55:48

对于那些与其他版本有问题的人来说,还有一个版本可供尝试。 它汇集了 这个重复的问题,并动态生成所需的帮助器 DIV,因此不需要额外的 HTML。

CSS:

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

JQuery:

function make_sticky(id) {
    var e = $(id);
    var w = $(window);
    $('<div/>').insertBefore(id);
    $('<div/>').hide().css('height',e.outerHeight()).insertAfter(id);
    var n = e.next();
    var p = e.prev();
    function sticky_relocate() {
      var window_top = w.scrollTop();
      var div_top = p.offset().top;
      if (window_top > div_top) {
        e.addClass('sticky');
        n.show();
      } else {
        e.removeClass('sticky');
        n.hide();
      }
    }
    w.scroll(sticky_relocate);
    sticky_relocate();
}

要使元素具有粘性,请执行以下操作:

make_sticky('#sticky-elem-id');

当元素变得粘性时,代码会管理剩余内容的位置,以防止其跳入粘性元素留下的间隙。 当滚动回其上方时,它还会将粘性元素返回到其原始非粘性位置。

Here's one more version to try for those having issues with the others. It pulls together the techniques discussed in this duplicate question, and generates the required helper DIVs dynamically so no extra HTML is required.

CSS:

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

JQuery:

function make_sticky(id) {
    var e = $(id);
    var w = $(window);
    $('<div/>').insertBefore(id);
    $('<div/>').hide().css('height',e.outerHeight()).insertAfter(id);
    var n = e.next();
    var p = e.prev();
    function sticky_relocate() {
      var window_top = w.scrollTop();
      var div_top = p.offset().top;
      if (window_top > div_top) {
        e.addClass('sticky');
        n.show();
      } else {
        e.removeClass('sticky');
        n.hide();
      }
    }
    w.scroll(sticky_relocate);
    sticky_relocate();
}

To make an element sticky, do:

make_sticky('#sticky-elem-id');

When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.

寒江雪… 2024-08-06 01:55:48

这就是我用 jquery 做到的。 这都是根据堆栈溢出的各种答案拼凑而成的。 该解决方案缓存选择器以获得更快的性能,并且还解决了粘性 div 变得粘性时的“跳跃”问题。

在 jsfiddle 上查看:http://jsfiddle.net/HQS8s/

CSS:

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

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);
        }
    });
});

This is how i did it with 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.

Check it out on jsfiddle: http://jsfiddle.net/HQS8s/

CSS:

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

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);
        }
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文