开发者

Setting div background image using JQuery

Im using JQuery to set the background image of a div as follows:

$(document).ready(function() {
    $('#pic').css("background","url(images/pic.jpg)");  

 });

But the image does not get displayed. How to fix this ?

Tha开发者_高级运维nk You.


maybe it also works with background but i always use

background-image

And also I always put quotes around the path

$('#pic').css("background-image","url('images/pic.jpg')"); 


Should work, but have you tried using "background-image" instead of "background"?

Also, can you navigate to the image through your browser correctly? I.e. yourdomain/images/pic.jpg?

Edit: Also, have you set a width and height for the div? The div will not auto-resize for a background image.


This is probably down to relative path issues.

What is the path (i.e the URL that appears in the browser navigation bar) for the page that contains the code that you posted? Where is this in relation to the images directory?

managing this can be a bit of a nightmare, especially if you've included a javascript file into multiple pages, that are at different levels within a URL hierarchy.

The better way to handle this, is to define a class, in a css file, make the image urls relative to the location of the css file itself, and then simply apply the class to your div, instead of setting individual style attributes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜