是否可以在 div 上使用材质 ui 的触摸波纹效果?

问题描述

我已经阅读过类似问题的不同答案,但它们都是旧的,并且在最新版本的材料 ui 中似乎不起作用。

我需要在 div 上应用触摸涟漪效果,但我不能使用按钮或 buttonBase 元素,因为里面有另一个按钮。

提前感谢您的回复

解决方法

Ciao Simone,是的,你可以(没有任何第三方库)。 我刚刚为您创建了一个游乐场:https://jsfiddle.net/youdede/njkft2eb/8/

说明

理想情况下,您有 div.container 并且在内部有一个用于涟漪效果 (.ripple) 和涟漪圆圈 (.ripple__circle) 的视口:

<div class="container">
  <div class="ripple js-ripple">
    <span class="ripple__circle"></span>
  </div>
  This is your content
</div>

每次用户点击波纹视口时,您都应该根据 .container 获取鼠标的位置并设置波纹圆圈的位置。

...
const $this = $(this);
const $offset = $this.parent().offset();
const $circle = $this.find('.ripple__circle');

const x = e.pageX - $offset.left;
const y = e.pageY - $offset.top;

$circle.css({
  top: y + 'px',left: x + 'px'
});
...

然后,您可以开始添加特定类的动画:

$this.addClass('is-active')

并在动画结束后立即将其删除:

$ripple.on('animationend webkitAnimationEnd oanimationend MSAnimationEnd',function(e) {
  $(this).removeClass('is-active');
});

每次添加 .is-active 类时都会执行以下动画(在 css 中指定):

@keyframes a-ripple {
  0% {
    opacity: 0;
  }
  25% {
    opacity: 1;
  }
  100% {
    width: 200%;
    padding-bottom: 200%;
    opacity: 0;
  }
}
,

是的,您可以使用 TouchRipple 来模拟涟漪效应。此组件未记录在案,但您可以查看它在 ButtonBase 中的使用方式并学习自己使用。

首先,您需要将 ref 传递给 TouchRipple 并分别在想要开始或停止效果时调用 ref.current.start(e)ref.current.stop(e)

e 是事件对象。当您调用 start(e) 时,它需要鼠标或触摸位置(来自 mousedowntouchstart 事件)才能知道从何处开始涟漪效应 (Source)。您可以通过将 center props 设置为 true 来覆盖此行为,这使得涟漪效应始终从中间开始。

以下是让您入门的最低工作示例:

function App() {
  const rippleRef = React.useRef(null);
  const onRippleStart = (e) => {
    rippleRef.current.start(e);
  };
  const onRippleStop = (e) => {
    rippleRef.current.stop(e);
  };

  return (
    <div
      onMouseDown={onRippleStart}
      onMouseUp={onRippleStop}
      style={{
        display: "inline-block",padding: 8,position: "relative",border: "black solid 1px"
      }}
    >
      Button
      <TouchRipple ref={rippleRef} center={false} />
    </div>
  );
}

现场演示

Edit 66888248/how-do-i-programatically-show-ripple-effect-with-material-ui