V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
wenxiang0207
V2EX  ›  程序员

[jquery 提问] 实现一个 button 对同一个文字的两种颜色切换。

  •  
  •   wenxiang0207 · 2017-03-06 11:32:16 +08:00 · 4261 次点击
    这是一个创建于 2608 天前的主题,其中的信息可能已经有所发展或是发生改变。
    之前用的.css("color","十六进制")但是做判断的时候浏览器读出来的是 rgb (???,0,0 )格式,所以我试图改成 hasclass 方法,但是也遇到了瓶颈,本人新手勿喷。
    求大神提点代码如下:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>webapp</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    $(document).ready(function(){
    $("button").click(function(){
    if($("[id='cha']").hasClass("text2")){
    $("[id='cha']").removeClass("text2").addClass("text3")
    }
    else ???
    })
    });
    </script>
    <style>
    .text2{
    color:#AA0000;
    }
    .text3{
    color:#55BB00;
    }
    </style>
    <p class="text1">hello world</p>
    <p id="cha" class="text2">im guy</p>
    <button type="button" >change
    </button>
    </body>
    </html>
    4 条回复    2017-03-06 13:59:34 +08:00
    Journey1969
        1
    Journey1969  
       2017-03-06 11:52:18 +08:00
    else 里面写 “ $("[id='cha']").removeClass("text3").addClass("text2") ” 不就能完成功能了吗?

    另外提几点小建议:
    1. style 标签应该放在<head></head>里面
    2. script 标签最好放在<body></body>里的最后
    xuexb
        2
    xuexb  
       2017-03-06 12:27:46 +08:00
    给个我的思路, 让按钮的默认颜色是 a, 添加个 class 颜色是 b, 在点击时使用 toggleClass('b')来切换颜色, 岂不是很方便?
    wenxiang0207
        3
    wenxiang0207  
    OP
       2017-03-06 13:42:14 +08:00
    @xuexb <body>
    <script type="text/javascript">
    $(document).ready(function(){
    $("button").click(function(){
    $("[class='text2']").toggleClass("text3")
    })
    });
    </script>
    <style>
    .text2{
    color:#AA0000;
    }
    .text3{
    color:#55BB00;
    }
    </style>
    <p class="text1">hello world</p>
    <p class="text2">im guy</p>
    <button type="button" >change
    </button>
    </body>
    我试图这样写,但是只能切换一次,再也切不回来了
    ren2881971
        4
    ren2881971  
       2017-03-06 13:59:34 +08:00
    难道不应该用 jquery 的 toggle 来实现么。。 不就是 点击按钮 然后切换同一个 dom 中字体的两种颜色么。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5254 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 09:31 · PVG 17:31 · LAX 02:31 · JFK 05:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.