HTML中的自定义游标

时间:2019-12-22 14:16:47

标签: javascript html css sass

我正在为网站创建自定义光标。当鼠标移动时,我有两个div居中于光标,但是当我将鼠标悬停在锚标记上时,背景光标的位置关闭了。我试过使用pageX和pageY将其放在for循环的中心,但是似乎不起作用。帮助吗?

这是我的HTML:

    <div class="cursor"></div>
    <div class="cursor-bg"></div>

CSS:

    .cursor{
        height:10px;
        width:10px;
        border-radius:50%;
        position:absolute;
        background: #fff;
        z-index: 100;

    }

    .cursor-bg{
        height:30px;
        :30px;
        border-radius:50%;
        position:absolute;
        background: $lightCursor-bg;
        transition-duration: 400ms;
        transition-timing-function: ease-out;

    }

    .expand{
        width: 100px;
        height: 100px;
        position: absolute;
        border:solid 1px #fff;
        background: rgba(255,255,255, 0);
    }

JS:

    (function(){
        var cursor = document.querySelector('.cursor');
        var cursorBg = document.querySelector('.cursor-bg');
        var navLinks = document.querySelectorAll('a');

        document.addEventListener('mousemove', e => {
            cursor.style.left = (e.pageX - 5) + 'px';
            cursor.style.top = (e.pageY - 5) + 'px';
            cursorBg.style.left = (e.pageX - 15) + 'px';
            cursorBg.style.top = (e.pageY -15) + 'px';

        });

       for (var i = 0; i < navLinks.length; i++) {

              var singleLink = navLinks[i];
              singleLink.addEventListener('mouseover', e => {
                  cursorBg.classList.add("expand");
                  cursorBg.style.left = (e.pageX - 50) + 'px';
                  cursorBg.style.left = (e.pageY - 50) + 'px';
              })

              singleLink.addEventListener('mouseout', e => {
                  cursorBg.classList.remove("expand");
              })
       }

     })();

1 个答案:

答案 0 :(得分:0)

您可以为此使用css cursor属性:

cursor: url(https://example.com/your-image.png), auto

演示:

div {
  width: 200px;
  height: 200px;
  background: dodgerblue;
  padding: 10px;
}

.custom-cursor {
  background: red;
  cursor: url(https://i.imgur.com/ng6jKDk.png), auto
}

p {
  font-family: sans-serif;
  text-align: center;
  font-size: 36px;
}
<div class="custom-cursor">
<p>Custom Cursor in this div only!</p>
</div>

<div>
<p>Not in this div!</p>
</div>

如果要将光标应用于整个页面,只需将CSS添加到正文中。

CSS cursor property