使用JavaScript的带有背景图像的径向光标

Radial cursor with Background Image using JavaScript

本文关键字:图像 光标 JavaScript 使用 背景      更新时间:2023-09-26

我正试图在一个带有背景图像的网站上创建一个径向光标。

我目前有两个问题:

  1. 它目前可以与Chrome兼容,但不能与Firefox兼容。当"background"出现解析错误时,我会收到它
  2. 在Chrome上,有时会出现两个光标而不是1,并且它似乎是镜像的,这可以在这个JSFiddle中看到

我目前正在使用从这里采用的以下代码。

我该怎么解决这个问题?谢谢

CSS:

        html { 
      background: url("blocpartylandscape.jpg") no-repeat center center fixed; 
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
    }

Javascript:

        $(function() {
        var originalBGplaypen = $("html").css("background"),
            x, y, xy, bgWebKit, bgMoz,
            lightColor = "rgba(255,255,255,0.75)",
            gradientSize = 100;
        var originalBG = $('html').css("background");
            $('html')
            .mousemove(function(e) {
                   x  = e.pageX - this.offsetLeft;
                   y  = e.pageY - this.offsetTop;
                   xy = x + " " + y;
                   bgWebKit = "-webkit-gradient(radial, " + xy + ", 0, " + xy + ", 100, from(rgba(255,255,255,0.8)), to(rgba(255,255,255,0.0))), " + originalBG;
                   bgMoz    = "-moz-radial-gradient(" + x + "px " + y + "px 45deg, circle, " + lightColor + " 0%, " + originalBG + " " + gradientSize + "px)";
                    $(this)
                        .css({ background: bgWebKit })
                        .css({ background: bgMoz });

            }).mouseleave(function() {
                $(this).css({ background: originalBG });
            }); 
    });

为了简化Firefox,我添加了另一个HTML元素。元素是围绕body中所有内容的容器。我这样做是为了使html元素可以具有其持久的背景图像,而不会被竞争的径向光标背景(也是图像)干扰。Chrome可以为背景图像和径向光标共享html元素,但Firefox不行。

<div class="container">
  <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi egestas in diam vitae elementum. </h1>
</div>

我使用新添加的容器作为画布,在画布上显示径向光标。

.container {
  height: 100vh;          
}

现在,在您的JavaScript中,我只需使用新的容器元素来显示放射状背景。

$(".container")
  .css({ background: bgWebKit })
  .css({ background: bgMoz });

然后用于删除径向光标。

.mouseleave(function() {
  $(".container").css({ background: originalBG });
}); 

Firefox还需要一个rgb或rgba值,而不是您对后台的调用返回的值。该值不是辐射状背景的有效参数,尽管以下内容是有效的:

bgMoz = "-moz-radial-gradient(" + x + "px " + y + "px 45deg, circle, " + lightColor + " 0%, rgba(255,255,255,0.0) " + gradientSize + "px)";

您可能需要进行更多的重构。我的主要目标是让事情为你运转。下面是一个适用于Chrome和Firefox的演示。

https://jsfiddle.net/7d17ufm7/