javascript - 使用 JavaScript 更改鼠标指针

标签 javascript mouse-cursor custom-cursor

我想使用脚本通过 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 将无法工作,除非您在图像光标之后指定一个默认光标!

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>

关于javascript - 使用 JavaScript 更改鼠标指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4564251/

相关文章:

javascript - CSS 光标事件变化

c# - 如何将透明光标渲染到保留 alpha channel 的位图?

javascript - 使用 CSS 为鼠标光标分配颜色

javascript - 自定义光标不适用于超链接

javascript - 如何使用类之类的东西将 onclick 代码移动到一个地方。在各种 html 标签处重复代码

javascript - 将html文本适当 chop 到固定大小的区域

javascript - 如何将表数据的类从 php 传递到 ajax/javascript

javascript - 如何在两个 div 之间的 contenteditable div 中设置插入符号/光标位置

jquery - 视网膜显示屏上的自定义光标清晰(真正有效的技术)

android - 选中复选框的 ListView 中行的位置