带有.css()串联问题的jQuery变量

jQuery Variable with .css() concatenation issue?

本文关键字:问题 jQuery 变量 css 带有      更新时间:2023-09-26

我正在尝试更改模糊按钮的CSS。我怀疑这可能是一个串联问题,但我无法弄清楚我做错了什么。这是我的密码。。。

HTML

<input type="text" value="blue" id="textinput">
<button>Button</button>
<span id="color">red</span>

CSS

button {
 background-color:blue;
 background-image: -webkit-linear-gradient(top, white 0%, black 100%);    
}

jQuery

$("#textinput").blur(function () {
     setTimeout(function () {
          endColor = $("#textinput").val();
          $('button').css({ 
              'background-color' : endColor
              'background-image' : '-webkit-linear-gradient(top, #309ACB 0%,' + endColor + '100%)'       });
     }, 500);
});​

FIDDLE链接

http://jsfiddle.net/krishollenbeck/p2jah/20/

当我删除渐变CSS时,它工作得很好。所以我猜我把变量连接错了。然而,我已经尝试了多种方法,但似乎都想不通。这可能是非常明显的事情。

另请注意。我正在使用webkit渐变,所以在chrome或safari中进行测试。提前感谢您的帮助。

在包含颜色和百分比字符串的变量之间缺少一个空白

'-webkit-linear-gradient(top, #309ACB 0%,' + endColor + ' 100%)'
                                                        ^
                                                        |
                                                        +-- Here

调试这种情况的一个好方法是使用console.log来查看连接字符串的结果。例如,在这种情况下,您将获得red100%而不是red 100%

imho不太容易出错的另一种选择是使用String.format()。这样,你就可以(更)清楚地看到你是否错过了什么:

'-webkit-linear-gradient(top, #309ACB 0%, {0} 100%)'.format(endColor)

请注意,有些浏览器不支持此功能,但您可以使用此pollyfill来定义它。

您缺少一个逗号和空格(请参阅Joao的答案)

$("#textinput").blur(function () {
     setTimeout(function () {
          endColor = $("#textinput").val();
          $('button').css({ 
              'background-color' : endColor, // < here        -> this way too               v here
              'background-image' : '-webkit-linear-gradient(top, #309ACB 0%,' + endColor + ' 100%)'       });
     }, 500);
});​