Setting background-image using jQuery CSS property

前端 未结 11 1973
渐次进展
渐次进展 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 10:51

    Here is my code:

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

    Enjoy, friend

    0 讨论(0)
  • 2020-11-22 10:51

    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");
    
    0 讨论(0)
  • 2020-11-22 10:52

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

    $('myObject').css('background-image', 'url(' + imageUrl + ')');
    
    0 讨论(0)
  • 2020-11-22 10:52

    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 + ')'})

    0 讨论(0)
  • 2020-11-22 10:56

    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.

    0 讨论(0)
  • 2020-11-22 11:00

    Try modifying the "style" attribute:

    $('myObject').attr('style', 'background-image: url("' + imageUrl +'")');
    
    0 讨论(0)
提交回复
热议问题