jQuery 悬停中断 toggleClass

jQuery hover interrupting toggleClass

下面是我的脚本。我打算做一些非常基本的事情,即在悬停在不同按钮(regular/inactive 和活动按钮)上时有不同的背景颜色。单击时,在两种状态之间切换。

现在,此代码可以正确悬停但不会切换。

<script type="text/javascript">
    $(".button").hover(
        function() {
            $(this).css("background-color", "#E4E4E4");
        },
        function() {
            $(this).css("background-color", "#EDEDED");
        }
    );
    $(".active").hover(
        function() {
            $(this).css("background-color", "#F5F9FF");
        },
        function() {
            $(this).css("background-color", "#EBF3FF");
        }
    );
    $(".button").click(function() {
        alert("The button is clicked!");
        $(this).toggleClass("active");
    });
</script>

而且,此代码确实会切换,但我必须禁用悬停才能实现

<script type="text/javascript">/*
    $(".button").hover(
        function() {
            $(this).css("background-color", "#E4E4E4");
        },
        function() {
            $(this).css("background-color", "#EDEDED");
        }
    );
    $(".active").hover(
        function() {
            $(this).css("background-color", "#F5F9FF");
        },
        function() {
            $(this).css("background-color", "#EBF3FF");
        }
    );*/
    $(".button").click(function() {
        alert("The button is clicked!");
        $(this).toggleClass("active");
    });
</script>

TL;DR 我无法同时使用 hover()toggleClass()。 注意:警报显示。

我加入了上面关于你试图在当时 DOM 中不存在的元素上生成的事件的评论。

您可以使用 css 设置元素样式,然后使用 javascript 在点击时触发 class。

$(".button").click(function() {
    $(this).toggleClass("active");
});
button {
    background-color: blue;
}

button:hover {
    background-color: royalblue;
}

button.active {
    background-color: purple;
}

button.active:hover {
    background-color: rebeccapurple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button">
  Click Me
</button>
<button class="button active">
  Click Me
</button>