2010-12-30 2 views
23

Volevo utilizzare uno script per modificare il puntatore del mouse sul mio sito Web utilizzando JavaScript. È meglio farlo con i CSS, ma il mio requisito è uno script che possa essere distribuito a molte persone da incorporare nella sezione principale dei loro siti web. Attraverso CSS, questo può essere manipolato daModificare il puntatore del mouse utilizzando JavaScript

html 
{ 
cursor: *cursorurl* 
} 

Come fare lo stesso in JavaScript?

risposta

31

Javascript è abbastanza bravo a manipolare i CSS.

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

o con jQuery:

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

Firefox non funziona se si specifica un cursore di default dopo l'immaginato uno !!

other cursor keywords

Ricordiamo inoltre che IE6 supporta solo .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> 
+0

Ho provato questo

10
document.body.style.cursor = 'cursorurl'; 
+0

Non funziona per me, solo con css ... –

6

Guardate questa pagina: http://www.webcodingtech.com/javascript/change-cursor.php. Sembra che tu possa accedere al cursore fuori dallo stile. Questa pagina mostra che si sta facendo con l'intera pagina, ma sono sicuro che un elemento figlio funzionerebbe altrettanto bene.

document.body.style.cursor = 'wait'; 
+0

Questo funziona, sulla premessa che il cursore sia effettivamente spostato, altrimenti rimane con il cursore esistente – s1cart3r

-1

Per quanto riguarda @CrazyJugglerDrummer secondo metodo sarebbe:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur"; 
+0

Questo non sta cambiando il cursore per me: - | Qui-> http://textb.in/39 – Cipher

-2

Oppure si può provare la seguente:

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

Per talvolta, target_element.style.property = value, non ha funzionato per me per ragioni sconosciute a me ...