Setting background-image using jQuery CSS property

前端 未结 11 2143
渐次进展
渐次进展 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: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');
    

提交回复
热议问题