Setting background-image using jQuery CSS property

前端 未结 11 1974
渐次进展
渐次进展 2020-11-22 10:34

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\', image         


        
相关标签:
11条回答
  • 2020-11-22 11:07

    String interpolation to the rescue.

    let imageUrl = 'imageurl.png';
    $('myOjbect').css('background-image', `url(${imageUrl})`);
    
    0 讨论(0)
  • 2020-11-22 11:10

    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');
    
    0 讨论(0)
  • 2020-11-22 11:12

    For those using an actual URL and not a variable:

    $('myObject').css('background-image', 'url(../../example/url.html)');
    
    0 讨论(0)
  • 2020-11-22 11:15

    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.

    0 讨论(0)
  • 2020-11-22 11:15
    $('myObject').css({'background-image': 'url(imgUrl)',});
    0 讨论(0)
提交回复
热议问题