366

コンテンツのブロックの下にある div を作成したいと思いますが、ページがスクロールされて上部の境界に達すると、所定の位置に固定され、ページとともにスクロールします。

4

22 に答える 22

323

単純に css を使用して、要素をfixedとして配置できます。

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

編集:絶対位置の要素が必要です。スクロールオフセットが要素に達したら、固定に変更し、上部の位置をゼロに設定する必要があります。

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 に達すると、要素はブラウザーウィンドウの上部に固定されます。

于 2009-08-01T08:05:46.817 に答える
250

この例は、Google Code の問題ページと (ごく最近) 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 docsを参照してください。

于 2010-01-28T10:30:59.867 に答える
33

私はあなたと同じ問題を抱えていたので、それを処理するために 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/dannyv/sticky-panel

デモ: http://htmlpreview.github.io/?https://github.com/dannyv/sticky-panel/blob/master/jquery.stickyPanel/Main.htm

于 2011-01-19T20:09:16.253 に答える
10

これは私が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);
        }
    });
});
于 2013-03-26T00:44:20.110 に答える
1

私の解決策は少し冗長ですが、中央に配置されたレイアウトの左端からの可変ポジショニングを処理します。

// 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));
    });
};
于 2012-11-15T22:34:02.940 に答える
1

他のバージョンで問題を抱えている人のために、もう 1 つのバージョンを試してみてください。この重複した質問で説明されている手法をまとめて、必要なヘルパー 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');

要素がスティッキーになると、コードは残りのコンテンツの位置を管理して、スティッキー要素によって残されたギャップにコンテンツが飛び込まないようにします。また、上にスクロールして戻ると、スティッキー要素を元の非スティッキー位置に戻します。

于 2013-08-05T21:00:43.913 に答える
1

同じものを探していたらこちらにたどり着きました。古い質問であることは承知していますが、より最近の回答を提供したいと思いました。

Scrollorama には、まさに私が探していた「ピン留め」機能があります。

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

于 2015-04-14T07:24:47.370 に答える
0

3つの行を追加して、ユーザーが上にスクロールして戻ると、divが古い場所にとどまるようにすることができます。

コードは次のとおりです。

if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed'){
    $('.fixedElement').css({'position': 'relative', 'top': '200px'});
}
于 2010-10-02T11:31:26.783 に答える
0

JavaScript では、次のことができます。

var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";
于 2013-05-29T22:55:42.437 に答える
0

この別の質問に答えるために提供された情報は、エヴァンの助けになるかもしれません:

スクロール後に要素が表示されるかどうかを確認する

基本的に、document.body.scrollTop 値が要素の上部以上であることを確認した後でのみ、要素のスタイルを変更して固定に設定する必要があります。

于 2009-08-01T08:13:19.140 に答える
0

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");
    });
});
于 2014-10-29T22:31:47.697 に答える
0

受け入れられた回答は機能しますが、上にスクロールしても前の位置に戻りません。そこに置かれた後、それは常に上にくっついています。

  $(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の応答は機能するはずですが、機能させることができませんでした。彼のサンプルページも機能しませんでした(私にとって)。

于 2010-07-08T14:29:02.760 に答える
0

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 admin@mydomain.com (Myvendor JavaScript Issue)');
    }
});
于 2010-11-11T13:58:50.820 に答える
0

上記の作業の一部を使用して、この技術を作成しました。私はそれを少し改善し、自分の作品を共有しようと思いました. お役に立てれば。

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

これは、スクロールを行う方法としてもう少し動的です。いくつかの作業が必要であり、ある時点でこれをプラグインに変えますが、これは私が何時間もの作業の後に思いついたものです.

于 2012-11-28T22:59:11.583 に答える