wangxinyun1995 / blogs

用issue记录我的博客
0 stars 0 forks source link

鼠标悬停为子div添加class #19

Open wangxinyun1995 opened 5 years ago

wangxinyun1995 commented 5 years ago
<!DOCTYPE html>
<html>
  <head>
    <title>mouse.html</title>
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <style>
        .child {
            width:100px;
            height:100px;
            background-color:red
        }
        .currentChild {
            width:120px;
            height:120px;
            background-color:black
        }
    </style>
    <script src="../../jquery/jquery-1.11/jquery.min.js"></script>
    <script>
    $(function() {
        //获取所有子div.
        var children = $('div#parent > div');

        //错误方法:会给所有子div添加class.
        /* children.mouseover(function(e) {
            children.addClass('currentChild');
        }).mouseout(function(e) {
            children.removeClass('currentChild');
        });  */

        //正确方法:通过each为每个子div添加class.
        children.each(function(i){
            //注意:this是js对象,$(this)是jquery对象.
            $(this).mouseover(function(e) {
                $(this).addClass('currentChild');
            }).mouseout(function(e) {
                $(this).removeClass('currentChild');
            });
        }); 
    });
    </script>
  </head>
  <body>
    <div id="parent">
        <div class="child">A</div><hr>
        <div class="child">B</div><hr>
        <div class="child">C</div><hr>
        <div class="child">D</div><hr>
        <div class="child">E</div><hr>
    </div>
  </body>
</html>