考虑到类,我如何使按钮 onclick 和悬停事件动态工作?

问题描述

我有 2 个按钮。 “关注”(灰色背景色)、“关注”(绿色背景色)。 (和推特一样的逻辑)

我想要的是,

  1. 当我点击“关注”按钮时,文本应更改为“关注”并且背景颜色应为绿色。
  2. 当我将鼠标悬停在“关注”按钮上时,其背景颜色应为红色,文本应为“取消关注”。当我单击该按钮时,文本应更改为“关注”并且背景颜色应为灰色。

我的 html 代码是:

<button class="b-unfollow" value="Following" style="background: green;">Following</button>
<button class="b-follow" value="Follow" style="background: grey;">Follow</button>
<script>
    $(document).ready(function() {
        $(".b-unfollow").attr("type","button");
        $(".b-follow").attr("type","button");
        
        $(".b-follow").click( function(){   
            $(this).text("Following");
            $(this).css("background","green");
            $(this).removeClass("b-follow");
            $(this).addClass("b-unfollow");
        });
        $(".b-unfollow").click( function(){ 
            $(this).text("Follow");
            $(this).css("background","grey");
            $(this).removeClass("b-unfollow");
            $(this).addClass("b-follow");
        }); 
        $(".b-unfollow").hover(function() {
            $(this).text("Unfollow");
            $(this).css("background","red");
        },function() {
            $(this).text("Following");
            $(this).css("background","green");
        });
    });
</script>

这是jsfiddle

问题 1:当我将鼠标悬停在绿色跟随按钮上时,它会变为红色背景并取消跟随文本。 (有用)。但是,当我单击该按钮时,最初按钮采用 Follow 的灰色背景,但是在 mouseleave 之后它又恢复原状。 第二个按钮的类似问题。 我哪里做错了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)