使用JavaScript更改鼠标指针

Cip*_*her 31 javascript cursor custom-cursor

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

html
{
cursor: *cursorurl*
}
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*son 38

Javascript非常擅长操纵css.

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

或者使用jquery:

$("html").css("cursor: url('cursor url with protocol'), auto");
Run Code Online (Sandbox Code Playgroud)

除非您在成像之后指定默认光标,否则Firefox 将无法工作!

其他光标关键字

还记得IE6只支持.cur和.ani游标.

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

// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)


Wal*_*ins 12

document.body.style.cursor = 'cursorurl';
Run Code Online (Sandbox Code Playgroud)


Bri*_*all 8

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

document.body.style.cursor = 'wait';
Run Code Online (Sandbox Code Playgroud)