javascript - 悬停时文件夹中的随机光标图像
问题描述
在一个简单的网页中,当我将鼠标悬停在我的元素上时,我试图获得一个随机光标图像。光标图像需要在 4 个 png 文件之间切换(下面为简单起见,我使用了系统光标,这不是问题)。我希望每次用户悬停元素时光标都会改变,而不必重新加载页面。
我在创建随机变化函数时遇到了麻烦。我想它需要是javascript或php。我在这两个方面都不是很胜任,并且在谷歌搜索解决方案方面没有成功。任何人的想法?
我试过用这个作为基础,虽然在这里你需要重新加载来改变光标,我希望光标在不重新加载的情况下改变。我已将 javascript 放在脚本下的头部,但它不起作用 - 但在 jsfiddle 中有效!不知道为什么。由于重新加载问题,我不确定这与我所需要的相差多远。
还尝试使用此php 片段作为基础,但根本不起作用。再次不知道为什么。
这是我的代码,没有光标的变化......我猜超级基本
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script>
</script>
</head>
<body>
<div style="background: #ee1; width:300px; height:300px;cursor: help;">
/* I'd like the cursor to change randomally every time the mouse returns to hover over the element. */
/* change between ['help', 'wait', 'crosshair'] */
</div>
</body>
</html>
解决方案
这是通过 JavaScript 完成的:
// The array for your cursors
var arrayOfCursors = ['help', 'wait', 'crosshair'];
// Selects the element
var el = document.getElementById('target');
//mouseover event
el.addEventListener("mouseover", function( event ) {
// Changes the cursor to a random from cursors array
el.style.cursor = arrayOfCursors[Math.floor(Math.random() * arrayOfCursors.length)];
});
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<script>
</script>
</head>
<body>
<div id="target" style="background: #ee1; width:300px; height:300px;">
/* The cursor changes randomally every time the mouse returns to hover over the element. */
/* changes between ['help', 'wait', 'crosshair'] */
</div>
</body>
</html>
推荐阅读
- arrays - Fortran 解除分配和数组形状
- python - 如何使用 ax.legend() 为条形图的子图添加公共图例
- nlp - amazon Lex 或 google dialogflow 上不支持的语言的解决方案
- javascript - TextField上出现错误帮助文本时如何更改边框颜色?
- go - 在开发/测试环境中使用 cloud.google.com/go/logging 时,有没有办法禁用日志转发到 GCP?
- python - 如何区分()具有混合值的时间序列数据
- laravel - 在下一个计费周期交换订阅 Laravel Cashier
- r - 重命名数据框列表中的第一个列名以匹配数据框的名称
- python - Telebot 消息重复
- javascript - 获取后渲染 React 的组件