鼠标为什么不能正常工作?

时间:2012-05-14 01:52:38

标签: javascript

javascript代码:

<script type="text/javascript">
          window.onload=function(){
            var Div1 = document.getElementsByClassName("title");
            var Div2 = document.getElementsByClassName("sub-menu");
            var timer=null;
            Div1.onmouseover = function (){
                clearTimeout(timer);
                Div2.style.display='block';

            };
            Div1.onmouseout=function(){
                timer=setTimeout(function(){
                   Div2.style.display='none';
                },300);

            };

            Div2.onmouseover =function(){
                clearTimeout(timer);
            };

            Div2.onmouseout=function(){
                 timer=setTimeout(function(){

                        Div2.style.display='none';
                     },300);


            };
        }

    </script>

html代码:

<div id="nav">
  <div class="left"></div>
  <div class="right"></div>
  <ul>
    <li><a href="/" class="current">Home</a></li>
    <li class="title"><a href="/cpanel.html" class="">cPanel</a>
      <div class="sub-menu">
      <div style="float:left">
          <h2>test</h2>
          <ul>
          <li>
              <a href="#">test</a>
          </li>
            <li>
              <a href="#">test</a>
          </li>
          </ul>
      </div>
  <div style="float:left">
          <h2>service</h2>
          <ul>
          <li>
              <a href="#">hello</a>
          </li>
            <li>
              <a href="#">hello</a>
          </li>
          </ul>
      </div>
</div>
    </li>





    <li class="title"><a href="/price.html" class="">Price</a>
    <div class="sub-menu">
        <ul>
          <li>
              <a href="#">hello</a>
          </li>
            <li>
              <a href="#">world</a>
          </li>
          </ul>
      </div>




    </li>

  </ul>
</div>

的CSS:

 #nav ul li{
    float: left;
    margin-right:50px;
    list-style: none;
    border-bottom: 1px solid red;
    position: relative;
    border: 1px solid red;
        }
#nav ul li .sub-menu{
    display: none;
    font-weight: normal;
    margin-top: 1px;
    padding: 0 10px 10px;
    position: absolute;
    text-align: left;
    width:auto;
    left: 10px;
    top:30px;
    border:1px solid #CCCCCC;
    width: 300px;
  }

js代码不起作用。当我将鼠标放在文本cpanel上时,它没有显示其下的相应内容。我不知道它有什么问题需要纠正它。提前谢谢。

1 个答案:

答案 0 :(得分:2)

getElementsByClassName()返回HTMLCollection。您需要通过将其视为数组来选择此集合的第一个元素:

var Div1 = document.getElementsByClassName("title")[0];
var Div2 = document.getElementsByClassName("sub-menu")[0];