Setting background-image using jQuery CSS property

2022-08-29 23:26:15

I have an image URL in a variable and I am trying to set it as CSS style, using jQuery:imageUrl

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

This seems to be not working, as:

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

returns .none

Any idea, what I am doing wrong?


答案 1

You probably want this (to make it like a normal CSS background-image declaration):

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

答案 2

You'll want to include double quotes (") before and after the imageUrl like this:

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

This way, if the image has spaces it will still be set as a property.