Native javascript learning: move the mouse in and out to change the style

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.