【问题标题】:When ViewPager move to next slide then previous slide should decrease opacity value for every move当 ViewPager 移至下一张幻灯片时,上一张幻灯片应降低每次移动的不透明度值
【发布时间】:2020-06-20 20:51:23
【问题描述】:

我的要求是当ViewPager 单击并拖动图像以获得下一张图像时,前一张图像应降低每次拖动的不透明度。这是我的codesandbox 代码。

这张图片是我要求的小例子。

import React, { useRef } from 'react'
import clamp from 'lodash-es/clamp'
import { useSprings, animated } from 'react-spring'
import { useDrag } from 'react-use-gesture'
import './styles.css'

function Viewpager() {
  const index = useRef(0)

  const [props, set] = useSprings(alphabets.length, i => ({
    x: i * window.innerWidth,
    scale: 1,
    opacity: 1,
    display: 'block'
  }))
  const bind = useDrag(({ active, down, movement: [mx], direction: [xDir], distance, cancel }) => {
    set(i => {
      if (i < index.current - 1 || i > index.current + 1) return { display: 'none' }
      const x = (i - index.current) * window.innerWidth + (down ? mx : 0)
      const scale = down ? 1 - distance / window.innerWidth / 2 : 1
      const opacity = active ? distance * 0.01 : 1
      return { x, scale, opacity, display: 'block' }
    })
  })

  return props.map(({ x, display, scale, opacity }, i) => (
    <animated.div
      {...bind()}
      key={i}
      style={{
        opacity,
        display,
        x
      }}
    />
  ))
}

我需要与codesandbox 代码相同的功能,并在将卡片拖动到其他卡片时并行降低不透明度。如果有人在其他库中有任何其他解决方案,例如framer-motion。这也很有帮助。

【问题讨论】:

    标签: reactjs animation react-spring framer-motion


    【解决方案1】:

    您应该将 x 值插入到不透明度中。 x 值介于 0 和负 innerWitdh / 2 之间。您应该将其传递以获取 1 到 0 之间的值。

    这是工作公式。

    opacity: x.to(x => 1 + x / (window.innerWidth / 2)),
    

    这是一个例子: https://codesandbox.io/s/card-slider-jwf3f

    旁注:

    如果您在屏幕上显示公式,您可以轻松检查公式。您所要做的就是将其作为animated.div 的文本。例如:

     <animated.div>{x.to(x => 1 - Math.abs(x / (window.innerWidth / 2)))}</animated.div>
    

    【讨论】:

    • 1.滑动卡片时圆圈大小不应该减小
    • 2.当滑动到下一张卡片时,下一张卡片的不透明度不应降低
    • 当第二张卡片拖动到第一张卡片时,第二张卡片的不透明度应该降低,第一张卡片的不透明度不应该降低,这意味着不透明度从左到右拖动效果很好,但从右到左拖动效果不佳
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2017-09-27
    相关资源
    最近更新 更多