簡體   English   中英

未捕獲的TypeError:無法設置未定義的屬性“背景”

[英]Uncaught TypeError: Cannot set property 'background' of undefined

我正在嘗試在頁面加載時加載CSS背景圖像,但出現此錯誤

未捕獲的TypeError:無法設置未定義的屬性“背景”

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();

由於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 + ')');

正如您提到的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM