且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-31 23:43:28

考虑一个 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>