使用Javascript的随机光标图像 [英] Random Cursor Images with Javascript

查看:43
本文介绍了使用Javascript的随机光标图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个简单网页的中间有一个div.将鼠标悬停在此div上时,我希望光标随机更改为自定义图像.我知道如何使用CSS设置自己的光标图像.但是,每次刷新页面时,如何使用javascript使此光标图像有所不同?

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?

此网站准确显示了我想要实现的目标.当我们将鼠标悬停在图像上时,光标会变成一个小图标,每次刷新页面时,该图标都会有所不同. https://glossier.com/#!/

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

谢谢.

推荐答案

您需要一个游标数组,一个用于随机选择一个游标的函数,您需要选择元素,最后需要使用以下方法更改元素的样式cursor属性.像这样:

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>

很难读到我发表的评论,所以这是您应该如何引入自己的自定义游标的方法:

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)您可以像这样将它们保存在 arrayOfCursors 中:

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

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

2)或如果它们都在同一个文件夹中,则可以执行以下操作:

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

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

,然后将文件名(带有扩展名)保存在 arrayOfCursors 中.

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

这篇关于使用Javascript的随机光标图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆