单击另一个时,jQuery添加类删除

时间:2013-07-23 17:54:39

标签: jquery addclass

在单击下一个项目后,将元素返回到其起始位置时出现问题。

当用户将鼠标悬停在div.box的两个元素上时,当单击该元素时,元素应保持不变。单击打开/关闭相同项目时,此工作正常。问题是当单击下一个项目时,跨度保持在a.blanket中心。

代码:http://jsfiddle.net/MhLwH/3/

HTML:

<div class="box">
    <div class="img"></div>
    <a href="" class="blanket">
        <span class="arrow"></span>
    </a>
</div>

<div class="box">
    <div class="img"></div>
    <a href="" class="blanket">
        <span class="arrow"></span>
    </a>
</div>

CSS:

.box {
    width:200px;
    height:200px;
    background:red;
    float:left;
    margin-left:10px;
    margin-top:50px;
    position:relative;
    /*overflow:hidden*/
}
.blanket {
    width:100%;
    height:100%;
    position:absolute;
    top:100%;
    left:0;
    background:blue;
}
.blanket, .arrow {
   -webkit-transition: all 0.3s ease-in; 
}
.arrow {
    display:block;
    width:100px;
    height:100px;
    position:relative;
    background:black;
    top:-300px;
    z-index:9999;
}
.box:hover .blanket {
    top:0;
}
.box:hover .blanket span {
    top:53px;
}
.active {
    top:0;
}
.activeArrow {
    top:53px;
}

JS:

$('.box').find('a').click(function (e) {
    e.preventDefault();
        var $this = $(this);

        if ($this.is('.active')) {
            $this.removeClass('active');
            $this.find('span').removeClass('activeArrow');

        } else {
            $('a.active').removeClass('active');
            $this.addClass('active');
            $this.find('span').addClass('activeArrow');
        }
});

旁注我知道转换目前只针对webkit

3 个答案:

答案 0 :(得分:1)

我想你忘了这句话:

$('span.activeArrow').removeClass('activeArrow');

答案 1 :(得分:1)

解决方案已经提供给您,但我想与您分享我的简短版本。

$('.blanket').on("click", function(event){
    var $this = $(this);
    $this.toggleClass('active').find('span').toggleClass('activeArrow');
    return false;
});

Fiddle

答案 2 :(得分:0)

这是你要找的吗? http://jsfiddle.net/csFBA/

不确定是什么导致了您的问题,但是当您将代码设置得更干净时,事情会变得更加清晰......

// You really don't need to do a find('a') here... use the proper selector
$('.box a').click(function (e) {
    e.preventDefault();
        var $this = $(this);
        // Only do one call to get the active state
        var blnActive = $this.hasClass("active");
        // now remove the active class from this item
        $this.removeClass("active");

        if (blnActive) {
            $this.find('span').removeClass('activeArrow');
        } else {
            $this.addClass('active');
            $this.find('span').addClass('activeArrow');
        }
});

从您的描述中不太清楚您的确切问题是什么,但是清理您的jQuery可能会让您更接近您想要的位置。

相关问题