Change the mouse pointer using JavaScript

2019-01-17 10:13发布

I wanted to use a script to change the mouse pointer on my website using JavaScript. It's better done by CSS but my requirement is of a script that can be distributed to many people to embed in the head section of their websites. Through CSS, this can be manipulated by

html
{
cursor: *cursorurl*
}

How to do the same in JavaScript?

5条回答
淡お忘
2楼-- · 2019-01-17 10:35
document.body.style.cursor = 'cursorurl';
查看更多
混吃等死
3楼-- · 2019-01-17 10:35

Or you can try the following :

document.getElementById("id_of_target_element").setAttribute("style", "cursor:url(path_to_file.cur);")

For sometimes, target_element.style.property = value, hasn't worked for me due to reasons unknown to me...

查看更多
来,给爷笑一个
4楼-- · 2019-01-17 10:38

Javascript is pretty good at manipulating css.

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

or with jquery:

$("html").css("cursor: url('cursor url with protocol'), auto");

Firefox WILL NOT WORK unless you specify a default cursor after the imaged one!!

other cursor keywords

Also remember that IE6 only supports .cur and .ani cursors.


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>
查看更多
混吃等死
5楼-- · 2019-01-17 10:54

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';
查看更多
何必那么认真
6楼-- · 2019-01-17 10:54

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";
查看更多
登录 后发表回答