programing

스크롤된 후 화면 상단에 div를 고정하려면 어떻게 해야 합니까?

kingscode 2022. 10. 8. 16:53
반응형

스크롤된 후 화면 상단에 div를 고정하려면 어떻게 해야 합니까?

콘텐츠 블록 아래에 있지만 페이지가 상단 경계에 닿을 정도로 스크롤되면 제자리에 고정되고 페이지와 함께 스크롤되는 div를 만들고 싶습니다.

단순히 css를 사용하여 요소를 고정으로 배치할 수 있습니다.

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

편집: 절대 위치를 가진 요소가 있어야 합니다. 스크롤 오프셋이 요소에 도달하면 고정으로 변경하고 상단 위치를 0으로 설정해야 합니다.

스크롤 상단 기능을 사용하여 문서의 상단 스크롤 오프셋을 감지할 수 있습니다.

$(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에 도달하면 요소가 브라우저 창의 맨 위에 고정됩니다.는 고정된 상태로 배치되기 때문입니다.

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> 

간단한 라이브 데모도 하고

이 필요 없는 은 크크 a a a a a음음음음음음음음음 a a a a a a a a a a a a a a a a a a a a a.position: sticky이는 Chrome, Firefox 및 Safari에서 지원됩니다.HTML5 Rocks and Demo 및 Mozilla 문서에 대한 문서를 참조하십시오.

및56 시점에서는 으로 사용되는 가 2017년 1월 Chrome 56을 .position: stickyCSS c c

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

Firefox와 Chrome에서는 제 기능을 발휘합니다.

에서는 Safari를 .position: -webkit-sticky.

Internet Explorer 및 Edge 용으로 폴리필을 사용할 수 있습니다.https://github.com/wilddeer/stickyfill이 좋을 것 같습니다.

저도 당신과 같은 문제가 있어서 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

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>

이게 바로 제가 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);
        }
    });
});

다른 옵션은 다음과 같습니다.

자바스크립트

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:absoluteCSS 성 c

Josh Lee와 Colin't Hart가 말했듯이, 당신은 선택 사항으로 그냥 사용할 수 있습니다.position: sticky; top: 0;디브

또, 이것을 페이지 상부에 카피하거나, 외부 CSS 시트에 맞도록 포맷하기만 하면 됩니다.

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

교환만 하면 됩니다.#sticky_div's_name_here가 "div"일 , "div"일 경우, "div"일 경우,<div id="example">#example { position: sticky; top: 0; }.

가장 간단한 솔루션(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>

여기 다른 버전에 문제가 있는 사용자를 위해 사용할 수 있는 버전이 하나 더 있습니다.중복 질문에서 설명한 기술을 조합하여 필요한 도우미 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');

요소가 스틱 상태가 되면 코드가 나머지 콘텐츠의 위치를 관리하여 스틱 요소가 남긴 틈새로 뛰어들지 않도록 합니다.또한 위로 스크롤할 때 스틱 요소를 원래 비스틱 위치로 되돌립니다.

이 솔루션은 약간 상세하지만 중앙 배치의 경우 왼쪽 모서리부터 변수 위치를 처리합니다.

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

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

같은 것을 찾다가 우연히 발견했어요.오래된 질문인 건 알지만 좀 더 최근 답변을 드리려고 합니다.

Scrollorama에는 제가 찾던 핀 잇 기능이 있습니다.

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

이 질문에 답하기 위해 제공된 정보가 당신에게 도움이 될 수 있습니다, Evan:

스크롤 후 요소가 보이는지 확인

기본적으로 요소의 스타일을 변경하여 document.body.scrollTop 값이 요소의 맨 위 값 이상임을 확인한 후에만 고정으로 설정합니다.

승인된 답변은 작동하지만 위로 스크롤하면 이전 위치로 돌아가지 않습니다.그 위에 올려놓은 후에는 항상 위에 붙어 있어요.

  $(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의 반응이 효과가 있을 것 같았지만, 나는 그것을 작동시킬 수 없었다.그의 예시 페이지도 통하지 않았다

사용자가 맨 위로 스크롤할 때 div가 이전 위치에 고정되도록 3개의 행을 추가할 수 있습니다.

코드는 다음과 같습니다.

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

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

javascript에서는 다음을 수행할 수 있습니다.

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

다음은 jquery-displugin을 사용하는 예입니다.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");
    });
});

저는 이 기술을 만들기 위해 위의 작업 중 일부를 사용했습니다.조금 개선해서 작품을 공유하려고 했어요.이게 도움이 됐으면 좋겠다.

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

이것은 스크롤을 좀 더 역동적으로 하는 방법입니다.작업이 좀 필요해서 언젠가는 플러그로 만들겠지만, 이것이 제가 퇴근 후에 생각해낸 것입니다.

정확한 해결책은 아니지만 고려해야 할 훌륭한 대안

CSS ONLY 화면 상단 스크롤 바.CSS, JavaScript, JQuery, No Brain work(웃음)만으로 모든 문제를 해결.

바이올린을 즐겨라: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 ONLY 화면 상단 스크롤 바

바닥글이 div를 누를 때까지 sticky:

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

언급URL : https://stackoverflow.com/questions/1216114/how-can-i-make-a-div-stick-to-the-top-of-the-screen-once-its-been-scrolled-to

반응형