2014-07-20 34 views
0

基本上,我正在尝试加载图像,使整个图像占用浏览器框架的背景,而我一直能够静态地完成这个任务。我试图实现它,以便我可以动态加载随机生成的不同图像。使用Javascript和DOM在div元素中加载图像

如果我这样做使用document.body.style.backgroundImage="url('img/" + image.image + "')"; 我可以看到它加载的图像很好。但有时在图像底部边界附近会有空白。

理想情况下,我想一个div,但是,这也不会加载中设置它,我留下了一个白色的背景: document.getElementById("pic").style.backgroundImage = "url('img/" + image.image + "')"; 我也试过: document.getElementById("pic").style.background = "url('img/" + image.image + "')";

如果我指定静态图像在我的'图片'类的CSS,它完美的作品。 ex。 background: url("http://lorempixel.com/1600/1200/nature/") ;

这里的CSS:

body { 
    top:0px; 
    left:0px; 
    height:100%; 
    width:100%; 
    z-index:-1; 
    opacity:1; 
    background-repeat: no-repeat; 
    background-size: cover; 
} 
.pic { 
    position:fixed; 
    top:0px; 
    left:0px; 
    width:100%; 
    height:100%; 
    z-index:-1; 
    opacity:1; 
    background-repeat: no-repeat; 
    background-size: cover; 
} 

使用无论是身体,或者div元素就可以了我,只要我可以动态加载在帧图像无空格或重复。此外,我不明白为什么我不能获得动态加载的div的背景,如果有人能解释我在那里做错了什么。任何帮助,将不胜感激。

+0

能否请你在展示你的jsfiddle整个代码? –

回答

1

看来你是在div标签上设置class'pic',但是你得到的元素div是id('pic')。

要么,更改属性 '类' 为div元素上的 'PIC' vlaue '身份证',

像使用

<div id="pic"> 

,而不是

<div class="pic"> 

OR,使用getElementsByClassName()方法,如

document.getElementsByClassName("pic")[0].style.backgroundImage = "url('img/" + image.image + "')"; 

,而不是

document.getElementById("pic").style.backgroundImage = "url('img/" + image.image + "')";