JS更改存储在变量中的图像的光标

JS Change the cursor for an image stored in a variable

是否可以使用存储在变量中的自定义图像来更改光标?

我试过 setAttribute 或 .style.cursor,但似乎不起作用..

以下是我尝试过的一些示例:

var MyImage = MyImage.png;
document.getElementById("DivWithMouseOverEvent").style.cursor = MyImage;

我也试过:

var MyImage = MyImage.png;
document.getElementById("DivWithMouseOverEvent").setAttribute("cursor", MyImage);

想法是 MyImage 变量可能会根据用户的某些操作而改变。

我知道 Firefox 需要第二个光标选项,但我不知道如何使用变量来实现。

这是我的例子。希望能帮到你

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
  </head>
  <body>
    <h1 id="title">
      This is a static template, there is no bundler or bundling involved!
    </h1>
    <script>
      const cursor = "Ball.cur";
      const url = `url(${cursor}), auto`;
      const title = document.getElementById("title");

      title.style.cursor = url;
    </script>
  </body>
</html>

--------干脆运行这段代码直接确认请

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        .cursor{
            cursor: wait;
        }
        div.cursor{
            background-color: green;
            color: white;
        }
    </style>
</head>
<body>
    
    <div class="cursor" >
        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eos, nobis cupiditate mollitia expedita voluptatibus quas sunt? Voluptatibus neque harum pariatur, laboriosam facere autem dolor reiciendis, quas necessitatibus est, amet quia?
    </div>

    <script>
        
        
            $(function () {
                $('.cursor').on('mouseenter', function(){
                    $(this).css({'cursor': "url('https://ani.cursors-4u.net/others/oth-9/oth927.cur'), auto", 'color':'orange', 'padding': '8px'});
                })
            })
        
    </script>
</body>
</html>

给定的代码有几个问题。

图片定义不仅需要字符串,还需要url.

此外,回退是强制性的(不仅仅是 Firefox 需要)。

有关允许的内容的更多详细信息,请参阅 MDN

let MyImage = 'https://i.stack.imgur.com/LZ9aI.png';
document.getElementById("DivWithMouseOverEvent").style.cursor = 'url(' + MyImage + '), grab';
#DivWithMouseOverEvent {
  width: 50vw;
  height: 50vh;
  background: cyan;
}
<div id="DivWithMouseOverEvent"></div>