![](/img/trans.png)
[英]How to change the mouse pointer to the image that was clicked on in Javascript
[英]Change the mouse pointer using JavaScript
我想使用腳本來使用 JavaScript 更改我網站上的鼠標指針。 最好由 CSS 來完成,但我的要求是一個可以分發給許多人以嵌入他們網站的 head 部分的腳本。 通過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 和 .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>
看看這個頁面: http : //www.webcodingtech.com/javascript/change-cursor.php 。 看起來您可以從樣式中訪問光標。 這個頁面顯示它是用整個頁面完成的,但我相信子元素也能正常工作。
document.body.style.cursor = 'wait';
document.body.style.cursor = 'cursorurl';
只需執行document.documentElement.style.cursor = "my-cursor-here"
。 即使在沒有元素的位置(不像document.body
,它只適用於有元素的地方),這也會改變光標。
注意:當您的鼠標懸停在某些元素上時,這可能不起作用,例如<button>
。
關於@CrazyJugglerDrummer 第二種方法是:
elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";
或者,您可以嘗試以下操作:
document.getElementById("id_of_target_element").setAttribute("style", "cursor:url(path_to_file.cur);")
有時候,由於我未知的原因, target_element.style.property = value
不適用於我...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.