40

JavaScript を使用して、スクリプトを使用して Web サイトのマウス ポインターを変更したいと考えていました。CSS で行うほうがよいのですが、私の要件は、多くの人に配布して Web サイトのヘッド セクションに埋め込むことができるスクリプトです。CSS を介して、これを次のように操作できます。

html
{
    cursor: *cursorurl*
}

JavaScriptで同じことをする方法は?

4

5 に答える 5

47

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 および .ani カーソルのみをサポートしていることにも注意してください。

カーソルが変わらない場合: カーソルの下の要素をカーソル位置に対して相対的に移動する場合 (要素のドラッグなど)、要素を強制的に再描画する必要があります。

// 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>
于 2010-12-30T16:22:51.300 に答える
17

このページを見てください: http://www.webcodingtech.com/javascript/change-cursor.php。スタイルからカーソルにアクセスできるようです。このページは、ページ全体で行われていることを示していますが、子要素も同様に機能すると確信しています。

document.body.style.cursor = 'wait';
于 2010-12-30T16:23:10.720 に答える
13
document.body.style.cursor = 'cursorurl';
于 2010-12-30T16:22:22.800 に答える
-1

@CrazyJugglerDrummerの2番目のメソッドに関しては、次のようになります。

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";
于 2010-12-30T16:45:10.023 に答える