【问题标题】:if an element has a certain CSS value do this如果一个元素具有特定的 CSS 值,请执行此操作
【发布时间】:2013-08-13 21:56:56
【问题描述】:

当我的按钮被点击时,我会更改文本的颜色,
在此副本更改文本后,我想执行另一个操作。

我写了以下内容,但无法让控制台或警报工作​​: http://codepen.io/leongaban/pen/IltKJ

$('#my_button').unbind('click').bind('click', function () {

    $(this).css('background', '#666666');
    $('#my_button').css('color', '#f58733');

    if ($('#my_button').css('color') == '#f58733') {
        alert('my_button has the color orange');
    }

});

我尝试了从 Tamas's answer here 找到的 CSS。

关于为什么警报没有被击中的任何想法?

【问题讨论】:

  • 一些浏览器(我认为尤其是firefox)使用rbg(x,x,x)而不是#xxxxxx作为颜色。这可能是您面临的问题。
  • @Bucky24,这正是正在发生的事情。
  • 尝试使用类而不是直接设置颜色属性
  • 更好的选择是添加一个类。然后你可以使用.hasClass('abc')
  • 你为什么在一个地方使用$(this)而在另一个地方使用$("#my_button")

标签: javascript jquery css if-statement


【解决方案1】:

试试这个:

Codepen

$('#my_button').unbind('click').bind('click', function () {
    $(this).addClass('clicked');
    if ($('#my_button').is('.clicked')) { //or use $('#my_button').hasClass('clicked')
        alert('my_button has the color orange');
    }
});

【讨论】:

  • 谢谢! :D 单击该按钮后,我在加载页面时遇到问题。那么页面会加载,但颜色不会改变,我必须再次单击它才能改变颜色。所以我认为页面加载中断了颜色变化
【解决方案2】:

我更新了你的代码....在 Chrome 中测试:

$('#my_button').unbind('click').bind('click', function () {

 $(this).css('background', '#666666');
 $('#my_button').css('color', '#f58733');

 var color = $('#my_button').css('color');
 alert(color);

 if(color == 'rgb(245, 135, 51)'){
 alert('Hi');
 }

});

在这里查看:http://codepen.io/anon/pen/Dilux

【讨论】:

    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 2017-06-08
    • 2023-03-09
    • 2010-12-26
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2015-02-02
    相关资源
    最近更新 更多