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

Kri*_*eck 3 javascript jquery

我试图改变模糊按钮的CSS.我怀疑它可能是一个连接问题,但我无法弄清楚我做错了什么.这是我的代码......

HTML

<input type="text" value="blue" id="textinput">
<button>Button</button>
<span id="color">red</span>
Run Code Online (Sandbox Code Playgroud)

CSS

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

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);
});?
Run Code Online (Sandbox Code Playgroud)

FIDDLE LINK

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

当我删除渐变CSS时,它工作正常.所以我猜我连接错误的变量.但是我尝试过多种方式,但似乎无法弄明白.这可能是非常明显的事情.

另请注意.我正在使用webkit渐变,因此在chrome或safari中进行测试.在此先感谢您的帮助.

Joã*_*lva 5

您缺少保持颜色的变量和百分比字符串之间的空格.

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

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

使用的替代方案是imho,不易出错String.format().通过这种方式,您可以(更多)清楚地看到您是否遗漏了某些内容:

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

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


Ste*_*ins 5

你错过了一个逗号和空格(见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);
});?
Run Code Online (Sandbox Code Playgroud)