微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决考虑到类,我如何使按钮 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 举报,一经查实,本站将立刻删除。