实用的网站效果 鼠标划过改变该层背景
来源:广州中睿信息技术有限公司官网
发布时间:2012/10/21 23:25:16 编辑:admin 阅读 692
分析:鼠标经过时其背景色改变,移走时又恢复原来的背景色一共2个事件。ViewCode1<!DOCTYPEHTML>2<html>3<head>4<metahttp-equ

分析:鼠标经过时 其背景色改变,移走时 又恢复原来的背景色 一共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 }


这样你想要的效果就会出现了。。。

联系我们CONTACT 扫一扫
愿景:成为最专业的软件研发服务领航者
中睿信息技术有限公司 广州•深圳 Tel:020-38931912 务实 Pragmatic
广州:广州市天河区翰景路1号金星大厦18层中睿信息 Fax:020-38931912 专业 Professional
深圳:深圳市福田区车公庙有色金属大厦509~510 Tel:0755-25855012 诚信 Integrity
所有权声明:PMI, PMP, Project Management Professional, PMI-ACP, PMI-PBA和PMBOK是项目管理协会(Project Management Institute, Inc.)的注册标志。
版权所有:广州中睿信息技术有限公司 粤ICP备13082838号-2