You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bootstrap 3 Modal点击按钮后滚动到指定锚点的实现问题

Solution for Scrolling to Anchor in Bootstrap 3 Modal

Hey, I see you've already nailed grabbing the anchor value from the button's data-anchor attribute—great start! The key issue here is that the show.bs.modal event fires before the modal is fully visible and its content is laid out, so trying to scroll at that point won't work as expected. Let's tweak your code to fix this:

Step-by-Step Breakdown:

  • Switch to the shown.bs.modal event: This triggers only after the modal is completely rendered and visible, so we can accurately calculate the scroll position.
  • Target the modal's scrollable container: The .modal-body is the element that handles scrolling, so we'll focus on that.
  • Calculate the relative offset of your anchor element and adjust the scroll position accordingly.

Modified JavaScript Code:

$('#exampleModal').on('shown.bs.modal', function(event) {
  var button = $(event.relatedTarget);
  var anchorValue = button.data('anchor');
  var targetElement = $('#' + anchorValue);
  
  // Only proceed if the target anchor exists
  if (targetElement.length) {
    // Get the modal's scrollable body
    var modalBody = $(this).find('.modal-body');
    // Calculate the exact scroll position relative to the modal body
    var scrollPosition = targetElement.offset().top - modalBody.offset().top + modalBody.scrollTop();
    
    // Optional: Add smooth scroll animation (remove for instant jump)
    modalBody.animate({
      scrollTop: scrollPosition
    }, 300);
  }
});

Why This Works:

  1. shown.bs.modal ensures the modal's content is fully loaded and dimensions are known, so our scroll calculation is accurate.
  2. We check for the existence of the target element to avoid console errors if the anchor ID is mistyped.
  3. The relative offset calculation accounts for the modal's fixed positioning, which absolute offsets can't handle correctly.
  4. The animate method adds a polished smooth scroll effect—replace it with modalBody.scrollTop(scrollPosition); if you prefer an instant jump.

Full Working Code (All Combined):

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div>
  <button class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-anchor="a1">Button 1</button>
  <button class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-anchor="a2">Button 2</button>
</div>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal-Box</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <section>
          <article>
            <br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text
            <h2 id="a1">Headline 1</h2>
            <br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text
            <h2 id="a2">Headline 2</h2>
            <br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text<br>text
          </article>
        </section>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send</button>
      </div>
    </div>
  </div>
</div>

<script>
$('#exampleModal').on('shown.bs.modal', function(event) {
  var button = $(event.relatedTarget);
  var anchorValue = button.data('anchor');
  var targetElement = $('#' + anchorValue);
  
  if (targetElement.length) {
    var modalBody = $(this).find('.modal-body');
    var scrollPosition = targetElement.offset().top - modalBody.offset().top + modalBody.scrollTop();
    modalBody.animate({
      scrollTop: scrollPosition
    }, 300);
  }
});
</script>

Give this a test—click either button, and the modal will open and smoothly scroll to the corresponding headline. Adjust the animation duration (the 300 value) or remove the animation entirely if you want!

内容的提问来源于stack exchange,提问作者Tisbo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:32:38