Programing

Bootstrap에서 ScrollSpy의 오프셋을 어떻게 설정합니까?

lottogame 2020. 8. 26. 08:19
반응형

Bootstrap에서 ScrollSpy의 오프셋을 어떻게 설정합니까?


메인 콘텐츠 영역에 navbar가 상단에 고정되고 아래에 3div가있는 사이트가 있습니다.

부트 스트랩 프레임 워크에서 scrollspy를 사용하려고합니다.

div를지나 스크롤 할 때 메뉴에서 다른 제목을 성공적으로 강조 표시했습니다.

또한 메뉴를 클릭하면 페이지의 올바른 부분으로 스크롤됩니다. 그러나 오프셋이 잘못되었습니다 (탐색 막대를 고려하지 않았으므로 약 40 픽셀만큼 오프셋해야 함)

난에 표시되는 부트 스트랩 페이지 는 오프셋 옵션을 언급하지만 난 확실히 그것을 사용하는 방법을 모르겠어요.

나는 또한 scrollspy와 함께 사용할 수 있다고 말했을 때 의미하는 바가 $('#navbar').scrollspy()아니며 포함해야 할 위치가 확실하지 않아 모든 것이 작동하는 것 같습니다 (오프셋 제외).

오프셋이 data-offset='10'본문 태그에 있을 수 있다고 생각 했지만 아무런 효과가 없습니다.

나는 이것이 정말로 명백한 것 같은 느낌이 들었고 나는 그것을 놓치고 있습니다. 도움이 필요하세요?

내 코드는

...
<!-- note: the data-offset doesn't do anything for me -->
<body data-spy="scroll" data-offset="20">
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
    <div class="container">
    <a class="brand" href="#">VIPS</a>
    <ul class="nav">
        <li class="active">
             <a href="#trafficContainer">Traffic</a>
        </li>
        <li class="">
        <a href="#responseContainer">Response Times</a>
        </li>
        <li class="">
        <a href="#cpuContainer">CPU</a>
        </li>
      </ul>
    </div>
</div>
</div>
<div class="container">
<div class="row">
    <div class="span12">
    <div id="trafficContainer" class="graph" style="position: relative;">
    <!-- graph goes here -->
    </div>
    </div>
</div>
<div class="row">
    <div class="span12">
    <div id="responseContainer" class="graph" style="position: relative;">
    <!-- graph goes here -->
    </div>
    </div>
</div>
<div class="row">
    <div class="span12">
    <div id="cpuContainer" class="graph" style="position: relative;">
    <!-- graph goes here -->
    </div>
    </div>
</div>
</div>

...
<script src="assets/js/jquery-1.7.1.min.js"></script>
<script src="assets/js/bootstrap-scrollspy.js"></script>
</body>
</html>

부트 스트랩은 오프셋을 사용하여 스크롤링이 아닌 감시 만 해결합니다. 이것은 적절한 위치로 스크롤하는 것은 당신에게 달려 있음을 의미합니다.

이것을 시도해보십시오. 내비게이션 클릭에 대한 이벤트 핸들러를 추가하십시오.

var offset = 80;

$('.navbar li a').click(function(event) {
    event.preventDefault();
    $($(this).attr('href'))[0].scrollIntoView();
    scrollBy(0, -offset);
});

여기에서 찾았습니다 : https://github.com/twitter/bootstrap/issues/3316


Tim이 언급했듯이 트릭은 패딩을 활용하는 것입니다. 따라서 문제는 브라우저가 항상 앵커를 창의 정확한 상단으로 스크롤하기를 원한다는 것입니다. 텍스트가 실제로 시작하는 위치에 앵커를 설정하면 메뉴 막대에 의해 가려집니다. 대신 nav / navbar가 자동으로 사용할 컨테이너 <section>또는 <div>태그의 ID로 앵커를 설정합니다 . 그럼 당신은 당신을 설정해야 할 padding-top금액에 컨테이너 원하는 오프셋과 margin-top받는 사람 컨테이너에 대한 반대padding-top. 이제 컨테이너의 블록과 앵커는 페이지의 정확한 상단에서 시작되지만 내부의 콘텐츠는 메뉴 막대 아래까지 시작되지 않습니다.

일반 앵커를 사용하는 경우 위와 같이 컨테이너에서 네거티브 margin-top을 사용하여 동일한 작업을 수행 할 수 있지만 패딩은 없습니다. 그런 다음 <a target="...">컨테이너의 첫 번째 자식으로 일반 앵커 를 넣습니다 . 그런 다음 두 번째 자식 요소의 스타일은 반대이지만 같지만 margin-top선택기를 사용합니다 .container:first-child +.

이 모든 것은 <body>태그에 이미 헤더 아래에서 시작하도록 여백이 설정되어 있다고 가정합니다 . 이는 표준입니다 (그렇지 않으면 페이지가 방망이에서 막힌 텍스트로 렌더링됩니다).

여기에 실제 동작의 예가 있습니다. URL 끝에 # the-elements-id를 붙이면 ID가있는 페이지의 모든 항목에 연결할 수 있습니다. 모든 h 태그 ad dt 태그를 ids로 링크 가능하게 만들면 ( github처럼 ) 왼쪽에 약간의 링크를 삽입하는 일종의 스크립트를 사용합니다 . CSS에 다음을 추가하면 탐색 모음 오프셋이 자동으로 처리됩니다.

body {
    margin-top: 40px;/* make room for the nav bar */
}

/* make room for the nav bar */
h1[id],
h2[id],
h3[id],
h4[id],
h5[id],
h6[id],
dt[id]{
    padding-top: 60px;
    margin-top: -40px;
}

다음과 같이 즉석에서 scrollspy의 오프셋을 변경할 수 있습니다 (몸을 감시한다고 가정).

offsetValue = 40;
$('body').data().scrollspy.options.offset = offsetValue;
// force scrollspy to recalculate the offsets to your targets
$('body').data().scrollspy.process();

오프셋 값을 동적으로 변경해야하는 경우에도 작동합니다. (다음 섹션이 창의 중간 정도에있을 때 scrollspy를 전환하는 것을 좋아하므로 창 크기를 조정하는 동안 오프셋을 변경해야합니다.)


10의 오프셋을 원하면 이것을 머리에 넣으십시오.

<script>
  $('#navbar').scrollspy({
    offset: 10
  });
</script>

본문 태그는 다음과 같습니다.

<body data-spy="scroll">

에서 부트 스트랩 문제 # 3316 :

[This]는 스크롤 계산을 수정하기위한 것입니다. 실제 앵커 클릭은 이동하지 않습니다.

따라서 오프셋 설정 은 scrollspy가 페이지가 스크롤되었다고 생각하는 위치 에만 영향을 미칩니다 . 그것은 스크롤에 영향을주지 않습니다 당신은 앵커 태그를 클릭 할 때.

고정 된 navbar를 사용하면 브라우저가 잘못된 위치로 스크롤됩니다. JavaScript로이 문제를 해결할 수 있습니다.

var navOffset = $('.navbar').height();

$('.navbar li a').click(function(event) {
    var href = $(this).attr('href');

    // Don't let the browser scroll, but still update the current address
    // in the browser.
    event.preventDefault();
    window.location.hash = href;

    // Explicitly scroll to where the browser thinks the element
    // is, but apply the offset.
    $(href)[0].scrollIntoView();
    window.scrollBy(0, -navOffset);
});

그러나 scrollspy가 올바른 현재 요소를 강조 표시하도록하려면 오프셋을 설정해야합니다.

<body class="container" data-spy="scroll" data-target=".navbar" data-offset="70">

여기 JSFiddle에 대한 완전한 데모가 있습니다 .


또는 CSS 트릭에서 제안한 대로 앵커 태그를 패딩 할 수 있습니다.

a[id]:before { 
  display: block; 
  content: " ";
  // Use the browser inspector to find out the correct value here.
  margin-top: -285px; 
  height: 285px; 
  visibility: hidden; 
}

오프셋이 섹션의 하단 위치에 뭔가를 할 수 있다고 생각합니다.

I fixed my issue - the same as yours - by adding

  padding-top: 60px;

in the declaration for section in bootstrap.css

Hope that helps!


I added 40px-height .vspace element holding the anchor before each of my h1 elements.

<div class="vspace" id="gherkin"></div>
<div class="page-header">
  <h1>Gherkin</h1>
</div>

In the CSS:

.vspace { height: 40px;}

It's working great and the space is not chocking.


Bootstrap 4 (2019 update)

Implementing: Fixed Nav, Scrollspy, and Smooth Scrolling

This is the solution from @wilfred-hughes above, it exactly fixes the overlap issue with the Bootstrap Fixed Navbar by using CSS '::before' to prepend an non-displayed block before each section tag. Advantage: you don't end up with unnecessary padding between your sections. Eg, section 3 can be vertically positioned right up against section 2 and it will still scroll to the exact correct position at the top of section 3.

Side note: setting the scrollspy offset in the script tag caused nothing to happen ( $('#navbar').scrollspy({ offset: 105 });) and attempts to adjust the offset in the animation block still resulted in misalignment post-animation.

index.html

<section id="section1" class="my-5">
...
<section id="section2" class="my-5">
...
<section id="section3" class="my-5">
...

later in index.html...

 <script>
      // Init Scrollspy
      $('body').scrollspy({ target: '#main-nav' });

      // Smooth Scrolling
      $('#main-nav a').on('click', function(event) {
        if (this.hash !== '') {
          event.preventDefault();

          const hash = this.hash;

          $('html, body').animate(
            {
              scrollTop: $(hash).offset().top
            },
            800,
            function() {
              window.location.hash = hash;
            }
          );
        }
      });
    </script>

style.css:

// Solution to Fixed NavBar overlapping content of the section.  Apply to each navigable section.
// adjust the px values to your navbar height
// Source: https://github.com/twbs/bootstrap/issues/1768
#section1::before,
#section2::before,
#section3::before {
  display: block;
  content: ' ';
  margin-top: -105px;
  height: 105px;
  visibility: hidden;
}

body {
  padding-top: 105px;
}

Credit: @wilfred-hughes above and the original source from user @mnot at https://github.com/twbs/bootstrap/issues/1768


I had problems with the solutions of acjohnson55 and Kurt UXD. Both worked for clicking a link to the hash, but the scrollspy offset was still not correct.

I came up with the following solution:

<div class="anchor-outer">
  <div id="anchor">
    <div class="anchor-inner">
      <!-- your content -->
    </div>
  </div>
</div>

And the corresponding CSS:

body {
  padding-top:40px;
}

.anchor-outer {
  margin-top:-40px;
}

.anchor-inner {
  padding-top:40px;
}

@media (max-width: 979px) {
  body {
    padding-top:0px;
  }

  .anchor-outer {
    margin-top:0px;
  }

  .anchor-inner {
    padding-top:0px;
  }
}

@media (max-width: 767px) {
  body {
    padding-top:0px;
  }

  .anchor-outer {
    margin-top:0px;
  }

  .anchor-inner {
    padding-top:0px;
  }
}

You will need to replace the 40px padding / margin with the height of your navbar, and the id of your anchor.

In this setup I can even observe an effect of setting a value for the data-offset attribute. If find large values for the data-offset around 100-200 lead to a more expected behavior (the scrollspy-"switch" will happen if the heading is circa in the middle of the screen).

I also found that scrollspy is very sensitive to errors like unclosed div tags (which is quite obvious), so http://validator.w3.org/check was my friend here.

In my opinion scrollspy works best with whole sections carrying the anchor ID, since regular anchor elements do not lead to expected effects when scrolling backwards (the scrollspy-"switch" eventually happens as soon as you hit the anchor element, e.g. your heading, but at that time you have already scrolled over the content which the user expects to belong to the according heading).


You can also open bootstap-offset.js and modify

$.fn.scrollspy.defaults = {
  offset: 10
}

there.


Just set :

data-offset="200"

data-offset is by default "50" and that is equivalent 10px, so just increase data-offset and your problem is solved.

참고URL : https://stackoverflow.com/questions/9288482/how-do-i-set-the-offset-for-scrollspy-in-bootstrap

반응형