使用JavaScript更改鼠标指针

时间:2010-12-30 16:19:14

标签: javascript cursor custom-cursor

我想使用脚本使用JavaScript更改我网站上的鼠标指针。 它最好由CSS完成,但我的要求是一个脚本,可以分发给许多人嵌入他们网站的head部分。 通过CSS,这可以通过

进行操作
html
{
cursor: *cursorurl*
}

如何在JavaScript中执行相同操作?

5 个答案:

答案 0 :(得分:36)

Javascript非常擅长操纵css。

 document.body.style.cursor = *cursor-url*;
 //OR
 var elementToChange = document.getElementsByTagName("body")[0];
 elementToChange.style.cursor = "url('cursor url with protocol'), auto";

或使用jquery:

$("html").css("cursor: url('cursor url with protocol'), auto");

Firefox 无法正常工作,除非您在成像后指定默认光标!

other cursor keywords

另请记住,IE6仅支持.cur and .ani cursors

如果光标没有改变:如果您要移动光标下的元素相对于光标位置(例如元素拖动),您必须强制重绘元素:

// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);

working sample:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First jQuery-Enabled Page</title>
<style type="text/css">

div {
    height: 100px;
    width: 1000px;
    background-color: red;
}

</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script></head>
<body>
<div>
hello with a fancy cursor!
</div>
</body>
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.cursor = "url('http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur'), auto";


</script>
</html>

答案 1 :(得分:13)

document.body.style.cursor = 'cursorurl';

答案 2 :(得分:8)

请看这个页面:http://www.webcodingtech.com/javascript/change-cursor.php。看起来你可以从样式访问光标。这个页面显示了整个页面的完成情况,但我确信子元素也可以正常工作。

document.body.style.cursor = 'wait';

答案 3 :(得分:-1)

关于@CrazyJugglerDrummer第二种方法,它将是:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

答案 4 :(得分:-2)

或者您可以尝试以下方法:

document.getElementById("id_of_target_element").setAttribute("style", "cursor:url(path_to_file.cur);")

有时,由于我不知道的原因,target_element.style.property = value对我不起作用......