我想使用脚本通过 JavaScript 更改我网站上的鼠标指针。 它最好由 CSS 完成,但我的要求是可以分发给许多人以嵌入到他们网站的头部部分的脚本。 通过 CSS,这可以被操作
html
{
cursor: *cursorurl*
}
如何在 JavaScript 中做同样的事情?
最佳答案
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 将无法工作,除非您在图像光标之后指定一个默认光标!
还要记住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>
关于javascript - 使用 JavaScript 更改鼠标指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4564251/