我在imageUrl变量中有一个图像URL,我试图将其设置为CSS样式,使用jQuery:

$('myObject').css('background-image', imageUrl);

这似乎并不奏效,因为:

console.log($('myObject').css('background-image'));

返回none。

知道我哪里做错了吗?


当前回答

除了其他答案,你还可以用“background”。当你想要设置与背景使用图像的方式相关的其他属性时,这特别有用,例如:

$("myObject").css("background", "transparent url('"+imageURL+"') no-repeat right top");

其他回答

你可能想要这样(使它像一个普通的CSS背景图像声明):

$('myObject').css('background-image', 'url(' + imageUrl + ')');

或者其他正确的建议,我发现它更容易通常切换CSS类,而不是个别的CSS设置(特别是背景图像url)。例如:

// in CSS 
.bg1 
{
  background-image: url(/some/image/url/here.jpg);
}

.bg2 
{
  background-image: url(/another/image/url/there.jpg);
}

// in JS
// based on value of imageUrl, determine what class to remove and what class to add.
$('myOjbect').removeClass('bg1').addClass('bg2');

除了其他答案,你还可以用“background”。当你想要设置与背景使用图像的方式相关的其他属性时,这特别有用,例如:

$("myObject").css("background", "transparent url('"+imageURL+"') no-repeat right top");

我遇到的问题是,我一直在加分号;在url()值的末尾,这会阻止代码工作。

❌不工作代码:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg);');
//--------------------------------------------------------------------------^

✅工作代码:

$('#image_element').css('background-image', 'url(http://example.com/img.jpg)');

注意省略的分号;在工作代码的末尾。我只是不知道正确的语法,而且真的很难注意到。希望这能帮助到其他处境相同的人。

$('myObject').css({'background-image': 'url(imgUrl)',});