我在一个简单网页的中间有一个 div。当我悬停这个 div 时,我希望我的光标随机更改为自定义图像。我知道如何使用 css 设置我自己的光标图像。但是如何使用javascript让每次刷新页面时这个光标图像都不一样呢?
这个网站准确地展示了我想要实现的目标。当我们将鼠标悬停在图像上时,每次刷新页面时光标都会变成一个不同的小图标。 https://glossier.com/#!/
提前致谢。
最佳答案
您需要一个光标数组,一个随机选择一个光标的函数,您需要选择元素,最后您需要使用光标属性更改元素的样式。像这样:
// The array for your cursors
var arrayOfCursors = ['pointer', 'crosshair', 'help', 'wait'];
// Returns a random element from the provided array
function random(arr){
var num = Math.floor(Math.random() * arr.length);
return arr[num];
}
// Selects the element
var el = document.getElementById('idName');
// Changes the cursor
el.style.cursor = random(arrayOfCursors);
#idName {
width:300px;
height:300px;
background:#eee;
}
<div id="idName"></div>
<hr />
<a href="javascript:location.reload(true)">Reload to see the effect again</a>
编辑:
很难阅读我在回复中发布的评论,因此您应该如何引入自己的自定义光标:
1) 您可以像这样将它们保存在 arrayOfCursors
中:
["url(images/my-cursor.png), auto", "url(images/other-cursor.png), auto"]
2) 或者如果它们都在同一个文件夹中,您可以执行以下操作:
el.style.cursor = "url(images/" + random(arrayOfCursors) + "), auto";
并将文件名(带扩展名)保存在 arrayOfCursors
中。
关于javascript - 使用 Javascript 的随机光标图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34114731/