首页 > 解决方案 > 悬停时文件夹中的随机光标图像

问题描述

在一个简单的网页中,当我将鼠标悬停在我的元素上时,我试图获得一个随机光标图像。光标图像需要在 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>

标签: javascriptphphtmlrandomcursor

解决方案


这是通过 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>


推荐阅读