【问题标题】:button changing its color按钮改变颜色
【发布时间】:2015-11-23 12:01:36
【问题描述】:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>moockup< /title>
        <style>
            .yellowBackground {
                background-color: yellow;
            }

            .redBackground {
                background-color: red;
            }
        </style>
    </head>

    <body>
        <button id="button" class="yellowBackground" id="thumb" >paina tästä< /button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>
            $(function() {
                $("#button").click(function() {
                    changeThumb();
                });
            });
            function changeThumb() {
                $("#thumb").toggleClass("yellowBackground redBackground");
            }
        </script>
    </body>
</html>

为什么这不起作用我想按下那个按钮,每次点击后它必须将颜色变为黄色和红色,我知道如何在 javascript 中做到这一点,但我现在正在学习 jQuery。

【问题讨论】:

  • 你的按钮标签中有两个 id....
  • 啊哈,我不能那样做吗?好的,我现在要做什么?

标签: jquery button colors


【解决方案1】:

这是一个解决方案:http://jsfiddle.net/leojavier/9psL0oa0/

<button class="yellowBackground" id="thumb" >test</button>

css

.yellowBackground {

background-color: yellow;
}

.redBackground {

background-color: red;
}

js

$("#thumb").click(function() {

   $("#thumb").toggleClass("redBackground");

});

【讨论】:

  • 希望这会有所帮助... :)
  • toggleClass 方法获取您要添加和删除的类名...您默认分配一个类,并且切换类应该覆盖默认类
  • 每个标签应该只有一个 ID 属性,并且在整个文档中应该是唯一的
  • 谢谢里奥哈维尔!!所以如果我有例如 我必须在一行中使用一个 id 吗?我可以使用很多类吗?
  • 您应该使用类...只要您想要许多具有相同行为的元素...例如 $(".thumb")
【解决方案2】:

希望这能回答您的问题。 小提琴[http://jsfiddle.net/57vss22x/3/]

jquery

$(".place").click(function () {
$(this).toggleClass("green");
});

css

.place { background-color: yellow; }
.place.green { background-color: red; }

HTML

<button id="button" class="place" id="thumb" >paina tästä</button>

【讨论】:

    【解决方案3】:

    一个元素中不能有多个 id 属性。

    $("#button").click(function() {
      changeThumb();
    });
    function changeThumb() {
      $("#button").toggleClass("yellowBackground redBackground");
    }
    .yellowBackground {
      background-color: yellow;
    }
    .redBackground {
      background-color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <button id="button" class="yellowBackground">paina tästä</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2015-10-25
      • 2018-11-12
      相关资源
      最近更新 更多