【问题标题】:Toggle addClass removes spanToggle addClass 删除跨度
【发布时间】:2013-08-14 14:32:07
【问题描述】:

我正在尝试构建一个网站,但是当我将 addClass 和 removeClass 与切换结合使用时,我的跨度在第一次单击时被删除。因此我无法再次点击我的跨度。

这是我的 HTML、脚本和 CSS:

HTML

<div id="footersi">
    <span class="footspans">First span</span>
    <span class="footspans">Second span</span>
    <span class="footspans">Third span</span>
    <span class="footspans">Fourth span</span>
    <span class="footspans">Fifth span</span>
    </div>    
    <div id="footerci">
    <span class="footspans" id="contactinf">Contactinfo</span>
        <ul class="index">
            <li><b>Li1</b></li>    
        </ul>
    </div>

脚本 (jQuery)

$(document).ready(function(){
    $(".index").hide();

    $("#contactinf").click(function(){
        $(this).toggle(
            function(){
                $(this).addClass('active');
            },
            function(){
                $(this).removeClass('active');
            }
        );
        $(".index").slideToggle();
        $("html, body").animate({ scrollTop: 1000 }, 600);
    });
});

CSS

.footspans {
    cursor:pointer;
    color:#9D9D9D;
    transition:color 0.2s ease 0s;
    -webkit-transition:color 0.2s ease 0s;
    font-size:1.1em;
    text-decoration:none;
    font-weight:bold;
    margin-right:20px;
}

.footspans:hover {
    color:black;
}

#footersi {
    float:left;
    width:740px;
}

#footerci {
    float:right;
    width:240px;
}

#contactinf {
    float:right;
    margin-right:5px;
}

.index {
    float:left;
}

.active {
    float:left;
    color:black;
}

【问题讨论】:

  • 我正在尝试在单击跨度时将浮动更改为“左”,所以是的,我想是的
  • 改用toggleClass()

标签: jquery css toggle html


【解决方案1】:

toggle() 正在切换元素的可见性,因此在第一次单击时它将隐藏元素,您将无法再次单击它。我相信你真正要找的是toggleClass()

$("#contactinf").click(function() {
    $(this).toggleClass("active");
});

【讨论】:

  • 好的,现在可以了,但是float属性还没有工作,这是因为'id'优先于'class'吗?
  • 如果我不得不猜测,是的,但我不能 100% 确定。
  • 嗯,margin 也不起作用.. 可能是因为我上面说的,现在要弄清楚了
  • 确实是这个问题,但是还没找到解决办法
  • 与其将样式应用于 ID,不如添加第二个类,然后也切换该类
猜你喜欢
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 2013-11-15
  • 2012-05-18
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多