【问题标题】:How do I bring the block up to the header by scrolling when the button is clicked?单击按钮时如何通过滚动将块带到标题?
【发布时间】:2023-02-07 20:37:13
【问题描述】:

我试图做到这一点,以便当您单击带有 .booking__button 类的按钮时,该块会在标题下方向上滚动。位置不应该改变,只能滚动。这样做是为了让用户可以看到预订模块的搜索结果。我找到了滚动的代码,但它使用确切的数字,现在是 100px,但你知道这个距离对每个人来说都是不同的,具体取决于屏幕的高度。

document.querySelector('.booking__button').addEventListener('click', () => {
  window.scrollTo(0, 100);
});
body {
  margin: 0;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: #002164;
}

.hero {
  min-height: calc(100vh - 100px);
  background: #fff;
}

.booking__module {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #BC0B3C;
}

.booking__search {
  height: 600px;
  background: #ccc;
}

.booking__button {
  height: 20px;
  margin: 40px;
}

.others {
  height: 200vh;
}
<header class="header"></header>
<main class="hero"></main>
<section class="booking">
  <div class="booking__module">
    <button class="booking__button">booking</button>
  </div>
  <div class="booking__search"></div>
</section>
<section class="others"></section>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    下面是一种方法,代码中有解释性的 cmets。请注意,虽然我更改了 &lt;header&gt; 元素的 background-color,但这只是为了可视化功能,根本不需要:

    // we pass a reference to the Event Object ('evt') to the function:
    document.querySelector('.booking__button').addEventListener('click', (evt) => {
      // we retrieve the closest ancestor <section> element of the element
      // to which the event-handler is bound, and retrieve the 'top' property
      // of its bounding-client rect:
      let {top} = evt.currentTarget.closest('section').getBoundingClientRect();
      
      // we then scroll to that value:
      window.scrollTo(0, top);
    });
    body {
      margin: 0;
    }
    
    .header {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      height: 60px;
      /*background: #002164;*/
      background-color: hsl(200deg 70% 70% / 0.4);
    }
    
    .hero {
      min-height: calc(100vh - 100px);
      background: #fff;
    }
    
    .booking__module {
      display: flex;
      justify-content: center;
      align-items: center;
      background: #BC0B3C;
    }
    
    .booking__search {
      height: 600px;
      background: #ccc;
    }
    
    .booking__button {
      height: 20px;
      margin: 40px;
    }
    
    .others {
      height: 200vh;
    }
    <header class="header"></header>
    <main class="hero"></main>
    <section class="booking">
      <div class="booking__module">
        <button class="booking__button">booking</button>
      </div>
      <div class="booking__search"></div>
    </section>
    <section class="others"></section>

    JS Fiddle demo

    参考:

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      相关资源
      最近更新 更多