jquery怎么判断标签是否有指定类,如果没有就添加,代码如下

实现鼠标移入时添加active类,鼠标移出删除active类,但是怎么判断在3个spebox都没有active类的时候,close的div添加active
$(function(){
$('#box1 .spebox').mouseover(function(){
$(this).addClass('active');
}).mouseout(function(){
$(this).removeClass('active');
})
if(! $('#box1 .spebox').hasClass('active')){
$('#box1 .close').addClass('active');
}
})

<body>
<div class="box1" id="box1">
<a><div class="close active spebox">

</div></a>
<a><div class="shose spebox">

</div></a>
<a><div class="access spebox">

</div></a>
</div>
</body>

这种mouseover和mouseout可以直接使用hover函数,判断在3个spebox都没有active类用if ($(".spebox.active").length == 0)

<!DOCTYPE html>
<!--STATUS OK-->
<html>

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta property="wb:webmaster" content="3aababe5ed22e23c" />
    <meta name="referrer" content="always" />
    <title>jquery怎么判断标签是否有指定类,如果没有就添加,代码如下_百度知道</title>
    <style>
        .spebox { display: inline-block; float: left; border: 1px solid #CCC; width: 100px; height: 40px; margin-right: 5px; }
        .spebox.active { background-color: #DDD; }
    </style>

    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(function () {
            $(".spebox").hover(function () {
                $(this).addClass("active");

                if (!$(this).hasClass("close")) {
                    $(".close").removeClass("active");
                }
            }, function () {
                $(this).removeClass("active");

                if ($(".spebox.active").length == 0) {
                    $(".close").addClass("active");
                }
            });
        });
    </script>
</head>

<body>
    <div class="box1" id="box1">
        <a>
            <div class="close active spebox"></div>
        </a>
        <a>
            <div class="shose spebox"></div>
        </a>
        <a>
            <div class="access spebox"></div>
        </a>
    </div>
</body>

</html>

追问

谢谢大神,还有个问题,为啥用mouseover和mouseout不行啊,用它写出来效果是乱的,换成hover就好了

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-05-09
$('#box1 .spebox').each(function(){
    if($(this).hasClass('close') && !$(this).hasClass('active')){
        $(this).addClass('active');
    }
})

第2个回答  2018-05-09
$(function(){
$('#box1 a').mouseover(function(){
$(this).find(".spebox").addClass('active');
$(this).siblings().find(".spebox").removeClass("active");
}).mouseout(function(){
$('#box1 .spebox').removeClass("active");
$("#box1 .close").addClass("active");
})
})

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网