0
美好的一天!我試圖設置一個div的背景圖像源與JavaScript,它似乎並沒有工作。我在控制檯中發現了一個奇怪的錯誤,我不知道該怎麼做。圖片無法正常加載
的代碼看起來可能有點冗長,但是我會盡量做到儘可能明確:
風格基本上包含3類。其中1個是存儲圖片和文本的大盒子。其他只是圖片(大小)和標籤(再次與大小)。 正文包含一個簡單的空div元素,它將是動態字段。
而剩下的就是JavaScript文件:陣列,從該「新聞」的不同的屬性將被讀取(如標題,圖,圖像源)
和最後的唯一功能的對象,它基本上創建新的div元素,給它們類並將它們附加到主元素上。錯誤在這裏。
的全部源代碼:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
.newsBox {
width:600px;
height:100px;
background-color:#B3CFDB;
float:left;
border-bottom: solid 1px;
border-bottom-color: #B9DDED;
}
.newsPic {
width:96px;
height:96px;
float:left;
margin-left: 4px;
margin-top:2px;
}
.newsLabel {
height:75px;
width: 500px;
background-color: white;
margin-top:20px;
float:left;
}
</style>
</head>
<body>
<div id="main" class="content"></div>
</body>
</html>
<script>
//create the object array and dummies
var arr = [];
var news = {
title: "",
views: 0,
srs: ""
};
var one = Object.create(news);
one.title = "Bender";
one.views = 132;
srs = "Bender.gif";
arr.push(one);
var two = Object.create(news);
two.title = "Salvation is upon us";
two.views = 777;
srs = "fryFuturama.jpg";
arr.push(two);
var three = Object.create(news);
three.title = "This website is a joke";
three.views = 0;
srs = "fry.jpg";
arr.push(three);
//Set up
var main = document.getElementById("main");
function loadNews() {
for (var i = 0; i < arr.length; i++) {
var p = document.createElement("DIV");
p.className = "newsBox";
main.appendChild(p);
var p1 = document.createElement("DIV");
p1.className = "newsPic";
p1.style.backgroundImage = "url(" + arr[i].srs + ")";
p.appendChild(p1);
var p2 = document.createElement("DIV");
p2.className = "newsLabel";
p2.innerHTML = arr[i].title + "</br></br>" + "Views: " + arr[i].views;
p.appendChild(p2);
}
}
loadNews();
</script>
編輯:錯誤:Resource interpreted as Image but transferred with MIME type text/html: "file:///C:/Users/SameTime/Desktop/ObjectSetBackgroundImage.html"
天啊......這是其中的一個錯誤。謝謝先生,它解決了問題! – Bloodcount
歡迎您。 – bugwheels94