ChatGPT解决这个技术问题 Extra ChatGPT

Setting background-image using jQuery CSS property

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

$('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?

What exactly is the issue? Is Jquery throwing an error?
No, its not setting it properly. I am logging it and it is just not changing.
The first time jQuery doesn't try to guess what the user meant.

D
Dessa Simpson

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

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

I was doing it this way - but a space between 'url' and the left parentheses was causing my code to fail. Copy/pasted yours and realized the issue. Thanks!
I using your code in this script but get me background-image: url((unknown)); This is my script: var bg_img = jQuery('.wp-show-posts-inner').attr('data-src'); jQuery('.wp-show-posts-inner').on('mouseover',function() { jQuery('.home-banner .bg').css('background-image', 'url(' + bg_img + ')'); }); Any idea why?
url() is not working for me. The value must be inside quotes i.e. url("") or url('').
A
Arosboro

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.


in that case, it should be $('myObject').css('background-image', 'url(' + encodeURIComponent(imageUrl) + ')');
This solved it for me. I needed to have the double quotes. My image names do contain spaces. Otherwise, nothing would occur. I could get something like $('.myObject').css('background-color', 'green'); to work, but not change the image without double quotes. Thanks!
encodeURIComponent won't work if part of your URL already contained URL escaped characters. You should escape potential double quote character in imageUrl though: $('myObject').css('background-image', 'url("' + imageUrl.replace(/"/g, '\\"') + '")');
By the by, doing $('#elem').css('background-image', 'url(' + encodeURIComponent(thumbData.url) + ')'); gave me background-image: url("%2Ffiles%2Fusers%2Fthumbs%2F36206608-hd-pics-3.jpg");
K
Kon

Alternatively to what the others are correctly suggesting, I find it easier usually to toggle CSS classes, instead of individual CSS settings (especially background image URLs). For example:

// 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');

This is a much better way to do things because it lets you use a css pre processor.
This is great, much better than the more direct solution.
This is going to load both images though.
Is this actually a recommended solution? It seems like this unnecessarily requires more information, e.g. in case there is a third possible background image, you will need to remove all other background images, or alternatively keep track of the "current" image. And also to have configuration details, such as these URIs in the .css files drives me crazy. :smiley: I have to search all over the code!
Using classes like this is also my preference since it lets you keep a clean seperation between code and style. I can then change all my images and animations in the css (via media selectors and such) without messing about with the code. You don't have to search all over the code if you keep your images OUT of the code!
A
Apo

Here is my code:

$('body').css('background-image', 'url("/apo/1.jpg")');

Enjoy, friend


M
Matt Parkins

Further to the other answers, you can also use "background". This is particularly useful when you want to set other properties relating to the way the image is used by the background, such as:

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

This answer made more sense when I thought the original op had used background not background-image. I've modified my answer to make more sense, and I'll leave this here for posterity anyway.
P
Prid

The problem I was having, is that I kept adding a semi-colon ; at the end of the url() value, which prevented the code from working.

❌ NOT WORKING CODE:

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

✅ WORKING CODE:

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

Notice the omitted semi-colon ; at the end in the working code. I simply didn't know the correct syntax, and it's really hard to notice it. Hopefully this helps someone else in the same boat.


This works perfectly as jQuery can append it to style property.
P
Pang

For those using an actual URL and not a variable:

$('myObject').css('background-image', 'url(../../example/url.html)');

a
appcropolis

Try modifying the "style" attribute:

$('myObject').attr('style', 'background-image: url("' + imageUrl +'")');

will replace all other styles. Not recommended
S
Sushanth --

String interpolation to the rescue.

let imageUrl = 'imageurl.png';
$('myOjbect').css('background-image', `url(${imageUrl})`);

A
Antony

Don't forget that the jQuery css function allows objects to be passed which allows you to set multiple items at the same time. The answered code would then look like this:

$(this).css({'background-image':'url(' + imageUrl + ')'})


This should be upvoted. Totally got used to the syntax .css( {...} )
w
wahaj
$('myObject').css({'background-image': 'url(imgUrl)',});

This won't work because the url is encased in single quotes.