当前位置:嗨网首页>书籍在线阅读

79-问题

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

5.19.1 问题

你的一个页面上有内联事件处理程序属性,为菜单创建悬停效果。

你的内容、表现(CSS)和行为(JavaScript)全都混在一起,难以单独维护,造成了JavaScript和样式设置的重复:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta http-equiv="Content-Language" content="en-us" />
   <title>Menu Demo</title>
   <style type="text/css">
     .menu {
        background-color: #ccc;
        list-style: none;
        margin: 0;
        padding: 0;
        width: 10em;
     }
     .menu li {
        margin: 0;
        padding: 5px;
     }
     .menu a {
        color: #333;
     }
   </style>
</head>
<body>
<ul class="menu">
   <li onmouseover="this.style.backgroundColor='#999';"
     onmouseout="this.style.backgroundColor='transparent';">
     <a href="download.html">Download</a>
   </li>
   <li onmouseover="this.style.backgroundColor='#999';"
     onmouseout="this.style.backgroundColor='transparent';">
     <a href="documentation.html">Documentation</a>
   </li>
   <li onmouseover="this.style.backgroundColor='#999';"
     onmouseout="this.style.backgroundColor='transparent';">
     <a href="tutorials.html">Tutorials</a>
   </li>
</ul>
</body>
</html>

5.19.2 解决方案 用jQuery事件处理程序代替内联JavaScript,添加/删除类代替直接操纵backgroundColor样式:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <meta http-equiv="Content-Language" content="en-us" />
   <title>Menu Demo</title>
   <style type="text/css">
     .menu {
        background-color: #ccc;
        list-style: none;
        margin: 0;
        padding: 0;
        width: 10em;
     }
     .menu li {
        margin: 0;
        padding: 5px;
     }
     .menu a {
        color: #333;
     }
     .menuHover {
        background-color: #999;
     }
   </style>
   <script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js">
   </script>
   <script type="text/javascript">
     $(document).ready( function() {
        $('li').hover(
          function() {
             $(this).addClass('menuHover');
          },
          function() {
             $(this).removeClass('menuHover');
          });
     });
   </script>
</head>
<body>
<ul class="menu">
   <li><a href="download.html">Download</a></li>
   <li><a href="documentation.html">Documentation</a></li>
   <li><a href="tutorials.html">Tutorials</a></li>
</ul>
</body>
</html>

我们已经删除了内联事件处理程序并用jQuery事件处理程序代替,隔离内容与行为。现在如果我们想添加更多的菜单项,就不必复制和粘贴同一批事件处理程序;这些事件处理程序会自动添加。

我们还将用于悬停效果的样式规则移到一个CSS类中,隔离行为和表现。如果我们以后想改变悬停效果的样式,只要更新样式表就可以了,没有必要修改标记。