簡體   English   中英

使用滾動捕捉時,如何將默認位置設置為第一列或第一行以外的位置?

[英]When using scroll snap, how can I set the default position to something other than the first column or row?

我有一個三列布局,我想在移動瀏覽器中滑動。 我正在使用 scroll-snap 為水平滾動定義三個可能的列/位置。 這似乎工作正常。

但是,我想將中間列設置為默認顯示,以便在首次呈現頁面(在移動設備上)時顯示中間列,並且用戶可以向右或向左滑動。

我可以使用 CSS 解決方案或滾動到中間位置的 javascript 解決方案。 我試過選擇各種元素並使用 scrollTo 或 scrollIntoView,但我要么遺漏了某些東西,要么無法完成。

這是一個代碼筆的鏈接,其中包含相關頁面的簡化版本: https ://codepen.io/kvinklly/pen/OJEejWe

以下是代碼筆中的 html 和 css:

<div class="container">
    <div class="item">
      <div>1</div>
    </div>
    <div class="item">
      <div>2</div>
    </div>
    <div class="item">
      <div>3</div>
    </div>
</div>
.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  border: 1px solid;
  width: 320px;
  height: 568px;
  scroll-snap-type: x mandatory;
  overflow-x: auto;
  white-space: nowrap;
  position: relative;
  -webkit-overflow-scrolling: touch;
}

.item {
  margin: 10px;
  display: flex;
  flex-direction: row;
  scroll-behavior: smooth;
  scroll-snap-align: center;
  justify-content: center;
  align-items: center;
  
  &:first-child {
    padding-left: 60px
  }
  
  &:last-child {
    padding-right: 60px;
  }
  
  div {
    display: flex;
    width: 200px;
    height: 300px;
    border: 1px solid red;
    border-radius: 15px;
    justify-content: center;
    align-items: center;
  }
}

好吧,chatGPT 來拯救。 答案很簡單(我將把它放入我自己修改過的代碼中以適合示例)。 你可以像這樣使用 JS 來做到這一點:

const container = document.getElementsByClassName('container')[0];
const middle = container.children[1];
middle.scrollIntoView();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM