未捕获的TypeError:无法设置属性' background'未定义的

时间:2016-05-13 09:44:32

标签: javascript jquery css3

我正在尝试在页面加载时加载css背景图像但我收到此错误

  

未捕获的TypeError:无法设置属性' background'未定义的

function loadBG() {
    document.getElementsByClassName("img-icon-invite").style.background = "url('<?php echo Yii::app()->theme->baseUrl; ?>/style/home/images/firstProPopup-sprite-new-white.png')";
    document.getElementsByClassName("img-icon-verified").style.background = "url('http://dev1.venturepact.com/themes/adminre/style/home/images/firstProPopup-sprite-new-white.png')";
}

window.onload = loadBG();

2 个答案:

答案 0 :(得分:3)

由于getElementsByClassName返回元素数组,您还需要指定索引,

document.getElementsByClassName("img-icon-invite")[0].style.background="url('<?php echo Yii::app()->theme->baseUrl;?>/style/home/images/firstProPopup-sprite-new-white.png')";

或者你可以使用Jquery,

$(".img-icon-invite").css('background-image', 'url(' + imageUrl + ')');

答案 1 :(得分:0)

正如你提到的jQuery:

function loadBG(){
        $(".img-icon-invite").css('background-image', "url('<?php echo Yii::app()->theme->baseUrl;?>/style/home/images/firstProPopup-sprite-new-white.png')";
        $(".img-icon-verified").css('background-image',"url('http://dev1.venturepact.com/themes/adminre/style/home/images/firstProPopup-sprite-new-white.png')";

}
$(document).ready(loadBG);