jQuery初学者:单击更改背景 [英] jquery beginner: change background on click

查看:52
本文介绍了jQuery初学者:单击更改背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据当前颜色更改单击元素的背景.

I'm trying to change the background of an element on click based on the current color.

以下是相关的html:

Here's the relevant html:

<div id="rect" style="height: 100px; width:300px; background: red">
</div>

和我的jquery尝试:

and my jquery attempt:

    $("#rect").click(function() {
    if ($(this).css('background') == 'red') {
        $(this).css('background','blue');}
    else {$(this).css('background','yellow');}
    });

我总是得到一个黄色的盒子; 真实"条件永远不会触发.

I'm always getting a yellow box; the 'true' condition never fires.

我在做什么错了?

推荐答案

更新

正如预期的那样,我在IE中发现了一个例外.要解决IE异常,只需使用jQuery的 .browser 方法.我已将其添加到以下示例代码中.

I found one exception, as expected, in IE. To account for IE exception, simply use jQuery's .browser Method. I've added this to below example code.

尝试:

$("#rect").click(function() {
    var red = $.browser.msie ? "red" : "rgb(255, 0, 0)";
    if ($(this).css('background-color') == red) {
        $(this).css('background','blue');}
    else {$(this).css('background','yellow');}
});

正如我在评论中解释的那样,jQuery将CSS属性的每个部分分解为背景",因此您需要调用所需的确切属性,在本例中为background-color.另外,jQuery将颜色值返回为RGB样式,因此红色将为rgb(255, 0, 0).现在,这并不能阻止.css("background" SET 背景有用,请记住,就像CSS一样, background 会覆盖所有其他背景直接属性.

As I explained in my comments, jQuery breaks down each part of CSS property "background", thus you need to call the exact Property you want, in this case background-color. Also, jQuery returns color values as RGB style, thus red would be rgb(255, 0, 0). Now this doesn't stop .css("background" from being useful to SET background, just remember, just like css, background will override all other background-direct properties.

显然有人为我制作了一个jsFiddle示例. (谢谢您 Sushanth )

Apparently someone made a jsFiddle example for me. (Thank you Sushanth)

在此处查看

@RyanKinal在他的评论中也指出了一个重点."jQuery甚至可能没有将颜色规范化为特定格式,因此不同的浏览器可能会以不同的格式返回颜色.这是需要注意的." 我尚未测试 ...

Also @RyanKinal make a good point in his comment "jQuery may not even normalize colors to a specific format, so different browsers may return colors in different formats. It's something to be aware of." I've not tested ...

通过不同浏览器返回的CSS红色":

CSS "red" as returned via different browsers:

  • Firefox 17:"rgb(255,0,0)"
  • Chrome 24:"rgb(255,0,0)"
  • 歌剧12:"rgb(255,0,0)"
  • Safari 5:"rgb(255,0,0)"
  • IE 7-9:红色"

这篇关于jQuery初学者:单击更改背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆