Dozens of lines of jQuery code realize the ripple effect of material design

Time:2021-11-12

Personal blog:Lingxiao’s blog

preface

As an MD party, I like the ripple effect of MD very much. The source codes found by Baidu are too complex, so I wrote one myself.

effect

Dozens of lines of jQuery code realize the ripple effect of material design

start

thinking

When clicking, locate the mouse and take the mouse as the ripple center to gradually expand the ripple and hide the place beyond

introduce

The radius of ripples defaults to the width or height of the element (the largest side)
The color and speed of ripples can be modified by yourself

code

$(function(){
  $(".ripple").click(function(e){
    if ($(this).find("#wave").length){
      $(this).find("#wave").remove();
    }
    $(this).append("<div id='wave'></div>");
    var wave=$(this).find("#wave");
    wave.css({
      "display": " block",
      //The color of ripples
      "background": " rgba(0, 0, 0, 0.3)",
      "border-radius": " 50%",
      "position": " absolute",
      "-webkit-transform": " scale(0)",
      "transform": " scale(0)",
      "opacity": " 1",
      //The speed of ripples
      "transition": " all 0.7s",
      "-webkit-transition": " all 0.7s",
      "-moz-transition": " all 0.7s",
      "-o-transition": " all 0.7s",
      "z-index": " 1",
      "overflow": " hidden",
      "pointer-events": " none"
    });
    //Gets the width and height of the ripple
    waveWidth = parseInt($(this).outerWidth());
    waveHeight = parseInt($(this).outerHeight());

    if(waveWidth < waveHeight){
      var R= waveHeight;
    }else {
      var R= waveWidth;
    }
    wave.css({
      "width":(R*2)+"px",
      "height":(R*2)+"px",
      "top": (e.pageY -$(this).offset().top - R)+'px',
      "left": ( e.pageX -$(this).offset().left -R)+'px',
      "transform":"scale(1)",
      "-webkit-transform":"scale(1)",
      "opacity":"0"
    });
  });
});

usage method

Add to your element.rippleclass

epilogue

The effect is to usejQueryYes, but I heard everyone abandoned itjQueryAll right, QAQ

Project address

Comments are welcome. Please point out any mistakes so as not to mislead more people