角4/5/6波纹效果指令

时间:2018-08-03 10:04:32

标签: angular typescript

任何人都可以帮助我在angular 4/5/6指令中转换下面的jQuery代码吗?我只想在项目中使用材料波纹效果,

$("div").click(function (e) {

// Remove any old one
  $(".ripple").remove();

  // Setup
  var posX = $(this).offset().left,
      posY = $(this).offset().top,
      buttonWidth = $(this).width(),
      buttonHeight =  $(this).height();

  // Add the element
  $(this).prepend("<span class='ripple'></span>");


 // Make it round!
  if(buttonWidth >= buttonHeight) {
    buttonHeight = buttonWidth;
  } else {
    buttonWidth = buttonHeight; 
  }

  // Get the center of the element
  var x = e.pageX - posX - buttonWidth / 2;
  var y = e.pageY - posY - buttonHeight / 2;

  $(".ripple").css({
    width: buttonWidth,
    height: buttonHeight,
    top: y + 'px',
    left: x + 'px'
  }).addClass("rippleEffect");
});

1 个答案:

答案 0 :(得分:0)

感谢@aloisdg,我自己做了,下面是代码

constructor(private renderer: Renderer2, private elem: ElementRef) {}

@HostListener('click', ['$event'])
  onClick(e) {
    const elemRenderer = this.renderer;
    const currentElem = this.elem.nativeElement;
    const rippleElem = currentElem.querySelector('.ripple');
    if (rippleElem) {
      elemRenderer.removeChild(currentElem, rippleElem);
    }

    // Setup
    const elemPosX = currentElem.getBoundingClientRect().left,
      elemPosY = currentElem.getBoundingClientRect().top;
    let elemWidth = currentElem.offsetWidth,
      elemHeight = currentElem.offsetHeight;

    currentElem.insertAdjacentHTML(
      'afterbegin',
      '<span class="ripple"></span>'
    );

    // Make it round!
    if (elemWidth >= elemHeight) {
      elemHeight = elemWidth;
    } else {
      elemWidth = elemHeight;
    }

    // Get the center of the element
    const x = e.pageX - elemPosX - elemWidth / 2;
    const y = e.pageY - elemPosY - elemHeight / 2;

    elemRenderer.setStyle(
      currentElem.querySelector('.ripple'),
      'width',
      elemWidth + 'px'
    );
    elemRenderer.setStyle(
      currentElem.querySelector('.ripple'),
      'height',
      elemHeight + 'px'
    );
    elemRenderer.setStyle(
      currentElem.querySelector('.ripple'),
      'top',
      y + 'px'
    );
    elemRenderer.setStyle(
      currentElem.querySelector('.ripple'),
      'left',
      x + 'px'
    );
    elemRenderer.addClass(currentElem.querySelector('.ripple'), 'rippleEffect');
  }