将鼠标悬停在按钮上后圆圈跟随光标

2022-01-22 00:00:00 hover mouse-cursor javascript html css

我正在尝试像在这个网站上一样重新制作悬停:

I'm trying to remake hover like on this website:

https://www.samsaraubud.com/

当您将鼠标悬停在一个按钮上(并且是唯一一个按钮.我不想在整个网站上圈子)时,光标周围会出现一个圆圈.输入鼠标跟随"后,我从 codepen 尝试了很多解决方案,但没有任何效果.

When you hover over a button (and only button. I don't want circle over whole website), a circle appers around cursor. I tried so many solutions from codepen after typing "mouse follow" but nothing works.

我有这样的按钮:

https://codepen.io/Aventadorrre/pen/mdyPJbv

body {
  padding: 100px;
  margin: auto;
}

a {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
}

<a href="#">Button</a>

当我悬停按钮时如何围绕鼠标(跟随鼠标)转圈?

and how to make circle around mouse (following mouse) when i hover button?

推荐答案

考虑一个 radial-gradient 作为背景,你使 fixed 然后简单地根据光标

Consider a radial-gradient as background that you make fixed then simply adjust the position based on the cursor

var h =document.querySelector('.cursor');

document.body.onmousemove = function(e) {
  /* 15 = background-size/2 */
  h.style.setProperty('background-position',(e.clientX - 15)+'px '+(e.clientY - 15)+'px');
}

body {
  padding: 100px 0;
}

a.cursor {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
  background:
    radial-gradient(farthest-side, 
     transparent calc(100% - 3px),
     red calc(100% - 2px) calc(100% - 1px),
     transparent 100%) 
     fixed /* Fixed to the screen*/ 
     no-repeat; /* Don't repeat*/

  background-size:30px 30px; /* Control the size of the circle */
  
}

<a class="cursor" href="#">Button</a>

如果你想要文字上方的圆圈考虑伪元素和相同的技巧:

If you want the circle above the text consider pseudo element and the same trick:

var h =document.querySelector('.cursor');

document.body.onmousemove = function(e) {
  h.style.setProperty('background-position',(e.clientX - 15)+'px '+(e.clientY - 15)+'px');
}

body {
  padding: 100px 0;
}

a.cursor {
  color: red;
  border: 2px solid red;
  padding: 20px 50px;
  background-size:0 0; 
  position:relative;
}
a.cursor::after {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:
    radial-gradient(farthest-side, 
     blue  calc(100% - 1px),
     transparent 100%) 
     fixed /* Fixed to the screen*/ 
     no-repeat; /* Don't repeat*/
  background-size:30px 30px;
  background-position:inherit;
}

<a class="cursor" href="#">Button</a>

相关文章