1

Как сделать кнопку, которая сразу стоит на месте, но если на нее навести и попробовать увести в сторону, то кнопка пойдет за мышкой, вот пример на сайте(белая кнопка со стрелочкой): https://www.m-trust.co.jp/.

3 ответа 3

2

Как-то так.

offset это расстояние от центра элемента, при котором будет происходить "разрыв" примагничивания.

let offset = 50, cur = false;

document.body.addEventListener('mouseenter', function(e) {
  if(e.target.classList.contains('magnetic') && cur === false) {
    cur = {
        e: e.target,
      x: e.target.getBoundingClientRect().left,
      y: e.target.getBoundingClientRect().top
    };
  }
}, true);

document.addEventListener('mousemove', function(e) {
    if(cur !== false) {
    let x = (e.clientX - cur.x) - (cur.e.getBoundingClientRect().width / 2),
            y = (e.clientY - cur.y) - (cur.e.getBoundingClientRect().height / 2);
    cur.e.style.transform = `translate(${x}px,${y}px)`;
    //
    if(Math.abs(x) >= offset || Math.abs(y) >= offset) {
        cur.e.style.transform = 'translate(0,0)';
      cur = false;
    }
  }
});
body {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  margin: 0;
}

.magnetic {
  transition: transform .2s linear;
}
<button class="magnetic">Magnet button</button>


Ответ скопирован с вопроса Как реализовать такую кнопку, чтоб она следовала за курсором, когда мышь рядом? [закрыт]

0

Почитай про MouseEvent client Property, MouseEvent screen Property и MouseEvent offset Property

Пример:

 let x = event.screenX; //достает положение мышки относительно экрана
 let y = event.screenY;
 let cord = "X: " + x + ", Y: " + y;
0

Сам искал. Вот, что используется на указанном сайте: https://codepen.io/riogrande/pen/bxmLYm

function buttonHoverAnimation() {
  // Get all button elements
  const buttonSelector = document.querySelectorAll(".button");

  // Loop through all button elements
  for (let i = 0; i < buttonSelector.length; i++) {
    // Get text inside of a button wrapped in span
    const buttonTextSelector = buttonSelector[i].querySelector("span");

    function mousemoveFn(event) {
      // Get X-coordinate for the left button edge
      const buttonPos = event.currentTarget.getBoundingClientRect().left;

      // Get position of the mouse inside element from left edge
      // (current mouse X position - button x coordinate)
      const xPosOfMouse = event.clientX - buttonPos;

      // Get position of mouse relative to button center
      // Mouse position inside element - button width / 2
      // To get positive or negative movement
      const xPosOfMouseInsideButton =
        xPosOfMouse - buttonSelector[i].offsetWidth / 2;

      // Button text divider to increase or decrease text path
      const animationDivider = 3;

      console.log(xPosOfMouseInsideButton);

      // Animate button text positive or negative from center
      TweenMax.to(buttonTextSelector, 2, {
        x: xPosOfMouseInsideButton / animationDivider,
        ease: Power3.easeOut
      });
    }

    // On mouse leave
    function mouseleaveFn() {
      // Animate button text reset to initial position (center)
      TweenMax.to(buttonTextSelector, 1, {
        x: 0,
        ease: Power3.easeOut
      });
    }

    buttonSelector[i].addEventListener("mousemove", mousemoveFn);

    buttonSelector[i].addEventListener("mouseleave", mouseleaveFn);
  }
}

buttonHoverAnimation();
body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

.button {
  transition: all 0.2s ease-in-out;
  position: relative;
  display: inline-block;
  vertical-align: middle;
  width: auto;
  min-width: 300px;
  text-align: center;
  white-space: nowrap;
  text-decoration: none;
  height: 75px;
  color: white;
  text-transform: uppercase;
  letter-spacing: 1.5px;
  background: transparent;
  border-color: transparent;
  overflow: hidden;
  cursor: pointer;
  font-family: "Work Sans", sans-serif;
}

button::before {
  content: "";
  transition: all 0.2s ease-in-out;
  position: absolute;
  z-index: -1;
  left: 0;
  top: 0;
  background-color: black;
  width: 100%;
  height: 100%;
}

button:hover::before {
  transform: scaleY(0.9);
}

button span {
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.10.4/gsap.min.js"></script>
<button class="button">
<span>Button text</span>
</button>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.