[英]jQuery - Change Background Image With Variable?
I'm trying to add a CSS background image with jQuery but can't seem to figure out how. 我正在尝试使用jQuery添加CSS背景图片,但似乎无法弄清楚该怎么做。 I THINK I'm along the right lines but I'm not sure... 我认为我的做法是正确的,但是我不确定...
var bgImg = "http://www.domain.com/my-image.jpg";
$('#myBanner').css("background", "url("+bgImg+");");
Here's a fiddle of it not working: http://jsfiddle.net/qLqvtkp3/ 这是一个不起作用的小提琴: http : //jsfiddle.net/qLqvtkp3/
Any help would be great!! 任何帮助将是巨大的!
You need to remove the ;
您需要删除;
in the string. 在字符串中。 it make the rule invalid and jQuery doesn't add invalid rule in the style
attribute. 它会使规则无效,并且jQuery不会在style
属性中添加无效规则。
$('#myBanner').css("background", "url("+bgImg+")");
http://jsfiddle.net/qLqvtkp3/17/ http://jsfiddle.net/qLqvtkp3/17/
用background
background-image
替换background
$('#myBanner').css("background-image","url('"+bgImg+"')");
Problems in your code :- 您的代码中的问题:
1)-You have concatenated your strings in the wrong way. 1)-您以错误的方式连接了字符串。
2)-You used background .You should use background-image . 2)-您使用了background 。您应该使用background-image 。
3)-You have written ;
3)-您已经写过;
in your jQuery css code ( "url("+bgImg+");")
) 在您的jQuery CSS代码中( "url("+bgImg+");")
)
Try this :- 尝试这个 :-
var bgImg = "http://www.domain.com/my-image.jpg";
$('#myBanner').css({"background-image":"url('"+bgImg+"')"});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.