2015-02-09 129 views
0

有没有什么办法用变量宽度代替255px以下的代码?有没有办法给jquery css方法添加变量?

var width = $(".input-textbox").width(); 

    $("#txtTryContactMob").css('background', '#fff url(\"/img/erroricon.png\") 255px center no-repeat'); 

我已经阅读了一点,并且我不想使用LESS css。

在此先感谢。

+2

''#fff url(\“/ img/erroricon.png \”)'+ width +'px center no-repeat''?你尝试过字符串连接吗? – 2015-02-09 14:22:53

+0

是的,但不同的方式:)看起来像我犯了一个错误,会尝试你的解决方案。 – Sheil 2015-02-09 14:23:38

+0

注意:您不需要在单引号字符串内转义双引号 – 2015-02-09 14:25:30

回答

1

您也可以在宽度从CSS样式的其余部分由专门靶向只是background-size风格分开:

var width = $(".input-textbox").width(); 
$("#txtTryContactMob").css('background', '#fff url("/img/erroricon.png") 255px center no-repeat') 
     .css('background-size', width); 

注意事项:

  • 它并不需要使用单个CSS属性时添加了px
  • 你没必要逃单引号的字符串
1

你可以使用这样的简单拼接

var customwidth = $(".input-textbox").width(); 
    $("#txtTryContactMob").css('background', '#fff url(\"/img/erroricon.png\") '+customwidth+'px center no-repeat'); 
1

里面的双引号要回答你的问题,“如何变量添加到jQuery的CSS的方法?”,也许哈希格式css看起来更加扩张:

$("#txtTryContactMob").css({ 
    "background": '#fff url("/img/erroricon.png") center', 
    "background-size": $(".input-textbox").width() + "px", 
    "background-repeat": "no-repeat", 
    "background-position": "center" 
    // more attribute pairs 
}); 

更多background详见http://www.w3schools.com/css/css_background.asp

相关问题