如何将innnerhtml内容设置为html部分背景图片网址

时间:2015-12-04 23:57:23

标签: javascript html

必须将innnerhtml内容设置为html部分背景图片网址。我已经尝试了很多方法,但缺少某些东西......他是代码......

function handle_setVals(xhr) {
    if (xhr.readyState == 4 && xhr.status == 200) {
         var data = eval("(" + xhr.responseText + ")");
         if (data['1']){
                   document.getElementById('f_bgimg_1').innerHTML = './images/' + data['1']['f_back_ground_PC'];

         }
    }
}

in html ...

<section id="result2-page" class="fullsize-page result2" style=background-image: url()>
</section>

要将f_bgimg_1设置为background-image:url().. 我已经尝试过隐藏的varibale,也喜欢这样

<section id="result2-page" class="fullsize-page result2" style=background-image: url(<span id='f_bgimg_1'></span>)>
</section>

不工作......提前谢谢......

1 个答案:

答案 0 :(得分:2)

您应该使用setAttribute方法在section代码中设置新样式:

document.getElementById("result2-page").setAttribute("style", "background-image: url()");

e.g:

(function() {
  var image = "http://mygimptutorial.com/images/button-with-reflection/11.jpg";
  document.getElementById("result2-page").setAttribute("style", "background-image: url(" + image + ")");
})();
.result2 {
  display: block;
  height: 169px;
  width: 498px;
}
<section id="result2-page" class="fullsize-page result2">
</section>