【问题标题】:css scroll snap isn't working on divs in React appcss scroll snap 不适用于 React 应用程序中的 div
【发布时间】:2019-07-14 01:22:01
【问题描述】:

我在不同的最新浏览器上对其进行了测试,因此它不会是兼容性问题。 我正在使用带有样式组件的 create-react-app,这是我的代码:

import React, { Component } from 'react';
import styled, { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css?family=Merriweather|Oleo+Script');
`

const Wrapper = styled.div`
  scroll-snap-type: y mandatory;
  display: flex;
  flex-direction: column;
  font-size: 16px;
`

const Home = styled.div`
  scroll-snap-align: center;
  height: 100vh;
  background-color: yellow;
  display: flex;
  flex-direction: row;
`

const Menu = styled.div`
  scroll-snap-align: center;
  height: 100vh;
  background-color: blue;
  display: grid;
`

const Speciality = styled.div`
  scroll-snap-align: center;
  height: 100vh;
  background-color: green;
`

class App extends Component {

  render() {
    return (
      <Wrapper>
        <GlobalStyle />
        <Home />
        <Menu />
        <Speciality />
      </Wrapper>
    );
  }
}

export default App;

当我滚动时它什么也没做,我几乎尝试过任何东西。 如果没有样式组件,它也将无法工作。

编辑:我将我的代码复制到代码框:https://codesandbox.io/s/72jmn1p1w1

【问题讨论】:

  • 它在 chrome 中滚动正常 - 它到底有什么作用?
  • @Mikkel 它应该像这样滚动:i.imgur.com/vMW8ALh.gif
  • 我也无法使用 React 中的样式组件使 css 滚动对齐。我已经集成了与snap.glitch.me/product.html 相同的代码,但无法正常工作。

标签: css reactjs scroll styled-components scroll-snap-points


【解决方案1】:

不要将scroll-snap-type: y mandatory应用于父div,而是尝试将其应用于html:

html {scroll-snap-type: y mandatory}

【讨论】:

    【解决方案2】:

    在您的代码沙箱中,我已将 Wrapper 元素代码替换为以下代码以使其正常工作:

    const Wrapper = styled.div`
      scroll-snap-type: y mandatory;
      max-height: 100vh;
      overflow-y: scroll;
    `;
    

    这解决了一些问题:

    • 明确说明包装器的高度,从而为内部元素创建一个“窗口”以捕捉到;
    • 将溢出设置为滚动或自动,因为子元素需要“隐藏”在包装器内,并且只有通过滚动才能看到滚动捕捉才能工作(并且有意义);
    • 移除 display: flex,因为它可能会迫使子元素调整其宽度或高度以适应容器,这与我们想要的相反——由于滚动高度,我们需要从视图中隐藏子元素/宽度。或者,您可以在子元素上使用 flex: 1 以防止它们调整大小,具体取决于您的用例。

    【讨论】:

      【解决方案3】:

      scroll-snap 我也遇到了一些问题。

      对我来说,如果没有 overflow-y: scroll,这将无法工作,请尝试将其放在您的 Wrapper 上。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-24
        • 1970-01-01
        • 2019-02-14
        • 2018-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多