Random Cursor Images with Javascript

半腔热情 提交于 2021-02-08 11:36:54

问题


I have a div in the middle of a simple webpage. When I hover this div, I want my cursor to change randomly to a customized image. I know how to set my own cursor image with css. But how to use javascript to make this cursor image different each time we refresh the page?

This website shows exactly what I want to achieve. When we hover an image, the cursor becomes a little icon that is different each time we refresh the page. https://glossier.com/#!/

Thanks in advance.


回答1:


You need an array of your cursors, a function to randomly select one, you need to select the element and finally you need to change the style of the element using the cursor property. Something like this:

// 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>

EDIT:

It was difficult to read the comment I posted in response so here's how you should be able to bring in your own custom cursors:

1) You could either save them in arrayOfCursors like this:

["url(images/my-cursor.png), auto", "url(images/other-cursor.png), auto"] 

2) OR If they're all in the same folder, you could do something like:

el.style.cursor = "url(images/" + random(arrayOfCursors) + "), auto";

and just save the name of the files (with extensions) in arrayOfCursors.



来源:https://stackoverflow.com/questions/34114731/random-cursor-images-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!