鼠标经过改变该层的背景
分析:鼠标经过时 其背景色改变,移走时 又恢复原来的背景色 一共2个事件。
View Code
1 <!DOCTYPE HTML>
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
5 <title>content type </title>
6 <style type="text/css" rel="stylesheet">
7 body { margin: 0; padding: 0; font-size: 12px; }
8 ul, li { margin: 0; padding: 0; list-style: none; }
9
10 .wrap { width: 960px; height: 800px; margin: 0 auto; padding: 25px; border: 1px solid #ccc; }
11 .pcon, .p-con { height: 25px; margin-top: 15px; border: 1px solid #ccc; }
12
13 </style>
14 </head>
15
16 <body>
17 <div id="box">
18 <div class="p-con">12143</div>
19 <div class="p-con">12143</div>
20 <div class="p-con">12143</div>
21 <div class="p-con">12143</div>
22 <div class="p-con">12143</div>
23 <div class="p-con">12143</div>
24 </div>
25 </body>
26 </html>
开始写js了,我最初的想法就是这样
View Code
1 function bg1(obj) {
2 obj.style.background = '#fcf1e3';
3 }
4
5 function bg2(obj) {
6 obj.style.background = '#fff';
7 }
8
在页面结构中直接调用就行了。 <div class="pcon" onmouseover = "bg1(this)" onmouseout = "bg2(this)" >12143</div>
这样问题就来了,如果需要加这样的功能好多个,难道我所有的都要加上这样的 onmouseover = "bg1(this)" onmouseout = "bg2(this)"的代码,感觉结构在视觉上给人的感觉很乱,不简洁。。。而且显得有些冗余。
1 //先获得 className
2 function getClassName(n) {
3 var classEle = []; allEle = document.getElementsByTagName("div");
4
5 for (var i = 0; i < allEle.length; i++) {
6
7 if (allEle[i].className == n) {
8 classEle[classEle.length] = allEle[i]; //把拥有这个classname为n 的元素 都存储到classEle的数组里。
9 }
10 }
11
12 return classEle;
13
14 }
15
16 function change() {
17 var pconClassName = getClassName('p-con');
18
19 for (var i = 0; i < pconClassName.length; i++) {
20 evt(pconClassName[i]);
21 }
22 }
23
24 //事件一些变化
25 function evt(obj) {
26 obj.onmouseover = function() {
27 obj.style.background = '#f00';
28 } ;
29
30 obj.onmouseout = function() {
31 obj.style.background = '#fff';
32 } ;
33 }
34
35 window.onload = function () {
36 change();
37 }
这样你想要的效果就会出现了。。。


浙公网安备 33010602011771号