【问题标题】:Class toggle working but rules not taking effect?类切换工作但规则不生效?
【发布时间】:2017-09-20 05:19:09
【问题描述】:

我有一个高度为 0 像素的导航 div,当我单击一个汉堡图标时,我想要添加一个高度为 250 像素的类。我正在使用事件侦听器来检测通过警报测试并正常工作的点击。然后使用ToggleClass() 添加类。

在开发者控制台中,我可以看到添加了类 ebing,但是 div 的高度没有改变,您还可以看到控制台中没有检测/显示高度规则,即使带有删除线。

这是来自开发控制台的相关信息的图像:https://gyazo.com/900f858cbfc41e9e8bfe00eb9fd8f1cb

styles.css:

#responsiveNav {
    position: absolute;
    right: 0;
    width: 200px;
    height: 0px;
    text-align: center;
    background-color: rgba(28, 28, 27, 0.8);
    color: #009641;
    margin-top: 100px;
    overflow: hidden;
    z-index: 1500;
    transition: all 0.8s ease;
}

.mobNavHeight {
    height: 250px;
}

JS:

$(document).ready(function () {
    var hamburgerBtn = document.getElementById("hamburgerBtn");

//DISPLAY MOBILE NAVIGATION ON HAMBURGER CLICK
    function displayMobNav() {
        alert("working");
        $('#responsiveNav').toggleClass("mobNavHeight");
    }

//EVENT LISTENERS
    hamburgerBtn.addEventListener("click", displayMobNav);


}); //Doc Ready

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    这是一个 CSS 特异性问题。 idclass 具有更高的特异性。在你的 CSS 中使用它。

    #responsiveNav.mobNavHeight {
        height: 250px;
    }
    

    但如果我是你,我首先不会使用 id 通过 CSS 定位元素。在 javascript 中只使用 id 定位,但在 CSS 中只使用 .responsiveNav 之类的类,将所有 #responsiveNav 样式移至该类,然后使用 .mobNavHeight 覆盖它。像这样。

    <nav id="responsiveNav" class="responsiveNav">nav</nav>
    
    .responsiveNav {
        position: absolute;
        right: 0;
        width: 200px;
        height: 0px;
        text-align: center;
        background-color: rgba(28, 28, 27, 0.8);
        color: #009641;
        margin-top: 100px;
        overflow: hidden;
        z-index: 1500;
        transition: all 0.8s ease;
    }
    
    .mobNavHeight {
        height: 250px;
    }
    

    【讨论】:

    • 感谢@MichaelCoker 现在工作。你的意思是ID具有更高的特异性?因为检测到的是 id 高度而不是类
    • @EthanBristow 是的,抱歉的意思是“更高”,已更新。由于这个原因,还更新了另一个建议,即一般不要在 CSS 中使用 id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多