我做了一个随机数字geny,我做了它,以便它改变背景中的图片。它可以是2个numers中的1个。她是代码(第一个css,然后是html
/* Basic Styles */
body {
background-color: #FBFBFB;
margin: 0;
padding: 0;
font-family: 'font', sans-serif;
}
@font-face {
font-family: font; src: url('font.ttf');
}
/* Hero Styles */
#hero{
text-align: center;
background: white;
margin: auto;
display: flex;
width: 100vw;
height: 65vh;
background-position: center -550px;
align-items: center;
justify-content: center;
}
#hero-title{
font-size: 5em;
color: white;
}

<!doctype html>
<html>
<head>
<title>
Hello
</title>
<link rel="stylesheet" href="style.css" />
<link rel='shortcut icon' href='images/favicon.ico' type='image/x-icon' />
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name = "viewport" content = "width = device-width">
<script type="text/javascript">
var hero=Math.random()
hero = (hero * 2)
hero = Math.floor(hero) + 1
console.log("Hero is number " + hero + " of 2.")
if (hero == 1) {
document.getElementById("hero").innerHTML.style.background-image="images/hero1.png"
}
</script>
</head>
<body>
<div id="hero">
<div id="hero-title">
awesome websogte
</div>
</div>
</body>
</html>
&#13;
答案 0 :(得分:2)
代码行中存在3个错误,这些错误应该设置背景图像。修复它,它会工作。
1:设置&#39; element.style&#39;而不是&#39; element.innerHTML.style&#39;。
2:更改&#39; background-image&#39;到&#39; backgroundImage&#39;。 (w3schools)
3:将图片链接包裹在&#39; url()&#39;。
中 旧: document.getElementById("hero").innerHTML.style.background-image="images/hero1.png"
新: document.getElementById("hero").style.backgroundImage="url(images/hero1.png)";