<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>鼠标移入移出改变样式</title> <style> body { color: #fff; font: 12px/1.5 Tahoma; /*字号和行高,字体*/ } #div1 { width: 150px; height: 150px; margin: 0 auto; /*左右置中*/ padding: 10px; background: black; /*默认背景色为黑色*/ border: 10px solid #000; cursor: crosshair; } #div1.hover { /*鼠标悬浮时的样式*/ color: red; background: #f0f0f0; /*背景色更改为浅灰色*/ border: 10px solid red; } </style> <script> window.onload = function () { var oDiv = document.getElementById("div1"); oDiv.onmouseover = function () { //设置div元素类 oDiv.className = "hover"; }; oDiv.onmouseout = function () { //去掉类 oDiv.className = ""; } } </script> </head> <body> <div id="div1">鼠标移入改变样式,鼠标移出恢复。</div> </body> </html>
说明:代码来自网络。注释为笔者学习时添加。