This is a simple example. first look at the demo:
Http://cssplusplus.com/demo/js/1_5_mouse_move_change_style0.html
The source code is as follows:
01 <! DOCTYPE html>
02 03 04 <style>
05 # box {width: 140px; height: 140px; margin: auto; background-color: black;
06 color: white; font: 12px/1.5 Tahoma; padding: 20px}
07 </style>
08
09 <script>
10 window. onload = function (){
11 var oBox = document. getElementById ("box ");
12 oBox. onmouseover = function (){
13 oBox.style.css Text = "background-color: red; color: green ";
14 };
15 oBox. onmouseout = function (){
16 oBox.style.css Text = "";
17}
18}
19 </script>
20 21 <body>
22 <div id = "box">
23 move the mouse to change the style, move the mouse to restore.
24 </div>
25 </body>
26 Modify oBox.style.css Text to modify the image.
(Note: cssText is equivalent to Dynamic Refresh embedded in html text. It has the highest priority. When cssText is cleared, the <style> </style> label or the style set by the external css file are not affected)
However, using cssText in javascript actually violates the style and behavior separation principles.
A better way is to use a hook, that is, add a class for the element using javascript, and set the class in the css file.
The improved source code is as follows:
View source
Print?
01 <! DOCTYPE html>
02 03 04 <style>
05 # box {width: 140px; height: 140px; margin: auto; background-color: black;
06 color: white; font: 12px/1.5 Tahoma; padding: 20px}
07 # box. hover {background-color: red; color: green}
08 </style>
09
10 <script>
11 window. onload = function (){
12 var oBox = document. getElementById ("box ");
13 oBox. onmouseover = function (){
14 oBox. className = "hover ";
15 };
16 oBox. onmouseout = function (){
17 oBox. className = "";
18 };
19 };
20 </script>
21 22 <body>
23 <div id = "box">
24 move the mouse to change the style, move the mouse to restore.
25 </div>
26 </body>
27
Author: Li yuhao