无法在我的HTML / JS页面上获得背景图片

时间:2018-09-27 14:38:12

标签: javascript css image css3 background

这是代码,我无法在身上或整个html上看到蛋糕的图像。我尝试过像正文背景一样的HTML,尝试过style,也尝试过js,但没有任何效果。有趣的是,我已经在其他页面上测试过图像,可以正常加载。我也尝试过使用html,css,js修改背景颜色,它们都可以正常工作。但是该死的图像不会加载。有什么想法吗?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Age Calculator</title>
</head>
<body>


  <style>
    #myDiv {
      background-image: url('images/cake.png');
      background-size: cover;
    }

    </style>

<div id="myDiv">
<script>

//document.body.style.backgroundImage = "url('images/cake.jpg')";
//document.getElementById("myDiv").style.backgroundImage =     "url('images/cake.jpg')";  


let birthYear = prompt("Enter Your Birth Year");
let birthMonth = prompt("Enter Your Birth Month (As A Number)");
let birthDay = prompt("Enter Your Birth Day");
let date = new Date();
let currentYear = date.getFullYear();
let currentMonth = date.getMonth() + 1;
let currentDay = date.getDate();
let yearAge = currentYear - birthYear;
let monthAge = currentMonth - birthMonth;
let dayAge = currentDay - birthDay;
let monthPluralizer = "";
let dayPluralizer = "";

if (monthAge === 1) {
  monthPluralizer = "Month";
} else {
  monthPluralizer = "Months";
}

if (dayAge === 1) {
  dayPluralizer = "Day";
} else {
  dayPluralizer = "Days";
}

if (currentMonth < birthMonth) {
  monthAge = monthAge + 12;
  yearAge = yearAge - 1;
}

if (currentDay < birthDay) {
  monthAge = monthAge - 1;
  if (currentMonth === 1 || 3 || 5 || 7 || 8 || 10 || 12) {
    dayAge = dayAge + 31;
  } else if (currentMonth === 4 || 6 || 9 || 11) {
    dayAge = dayAge + 30;
  } else if (currentMonth === 2) {
    dayAge = dayAge + 28;
  }
}

if (currentMonth == birthMonth && currentDay < birthDay) {
  monthAge = monthAge + 12;
  yearAge = yearAge - 1;
}


document.write("<p>Your Birth Date Is " + birthMonth + "/" + birthDay + "/" + birthYear + "</p><br>");
document.write("<p>Today's Date Is " + currentMonth + "/" + currentDay + "/" + currentYear + "</p><br>");
document.write("<p>You Are " + yearAge + " Years, " + monthAge + " " + monthPluralizer + " & " + dayAge +
  " " + dayPluralizer + " Old.</p><br>");
if (birthMonth == 0 && birthDay == 0 && birthYear == 0 ) {
  document.write("<p>Hello Jesus!<p>")
} else if (birthMonth === null && birthDay === null && birthYear === null ) {
  document.write("<p>Hello Jesus!<p>")
}





</script>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您的图片路径错误。

尝试一下:

   #myDiv {
      background-image: url('./images/cake.png');
      background-size: cover;
    }

如果不工作,请告诉我

您可以阅读有关HTML Paths here的更多信息,并在此问题here

中看到与您类似的另一篇文章

答案 1 :(得分:1)

您的图像路径不正确,应该更改路径。您可以在here

中了解如何定义路径