【问题标题】:Want to test the Name of a background color in JQuery想要在 JQuery 中测试背景颜色的名称
【发布时间】:2011-07-27 09:29:57
【问题描述】:

我没有找到我能理解的答案。我正在尝试测试被单击的 div 的背景颜色是否为“红色”...而不是红色(在警报中)我得到 rgb(125,0,0) .... 尝试使用单报价,它没有工作...请帮助?

 alert($('#' + id).css('background-color'));

 if ($('#' + id).css('background-color') == 'red') {
                 $('#' + id).hide('slow');
 }

【问题讨论】:

    标签: jquery background-color


    【解决方案1】:

    在 Chrome 中测试它,我在这些逗号之间得到了空格。如果是比较字符串,包括空格在内的每个字符都必须相同,所以改为:

    if ($('#' + id).css('background-color') == 'rgb(255, 0, 0)') {
    

    【讨论】:

      【解决方案2】:

      如果您使用 CSS 类为 div 赋予背景颜色,然后简单地测试该类的存在,那就容易多了。无论如何,颜色的语义不如类。

       <style>
          .alert { background-color: Red; }
       </style>
      
       <div id="warning" class="alert">
       </div>
      
       <script type="text/javascript">
          $(function() {
             $('div').click( function() {
                 if ($(this).hasClass('alert')) {
                      $(this).hide('slow');
                 }
             });
          });
       </script>
      

      【讨论】:

      • 啊,粗鲁,这样做更有意义——我将在我的红色 div 中添加一个类...谢谢!
      【解决方案3】:

      This 可能有助于避免任何可能的跨浏览器差异。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-11
        • 2013-01-28
        • 2022-12-12
        相关资源
        最近更新 更多