简体   繁体   中英

how do i change css background image using jquery?

$(document).ready(function() {
    $('#picture').css('height', '666px');
    $('#picture').click(function () {
        $(this).css('background-image', "url('../images/picture_2.jpg')");
    });
});

in the above code, the height is successfully changed to 666px but the background image does not change at all (remains the original one).

When I change the background-image to 'none' instead of "url('../images/picture_2.jpg')" it does make the background image disappear though.

What am I doing wrong?

My guess is that the URL you're putting in is incorrect. The URL should be relative to the page you're on . I bet your URL is relative to your CSS style sheet. In general, just use absolute paths when doing this in JS.

You also don't need the single quotes surrounding the path.

The code you provided should work fine. I think the image location you mentioned ../images/picture_2.jpg is incorrect. Check if you could see the image from that location in firebug.

I tried the same code and it worked fine for me. DEMO here

Correct the path to the image.

Path to the image will be calculated from the root of the site, not from the css.

Just to clarify :

Height will change on the load of the page, Where as Background image will change only if #picture element will be clicked.

Here is a demo , which works for me.

How does this differ from what you've tried?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM