再会!我正在尝试使用 javascript 设置 div 的背景图像源,但它似乎不起作用。我在控制台中收到一个奇怪的错误,我不知道该怎么做。
代码可能看起来有点长,但我会尽量让它清楚:
该样式基本上包含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"