我正在尝试为背景图片制作幻灯片。这是到目前为止的代码:
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "assets/Images/Image1.jpg";
images[1] = "assets/Images/Image2.jpg";
images[2] = "assets/Images/Image3.jpg";
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="CenterContents" onload = "changeImage()">
<%-- write everything here --%>
<img id="img" src="assets/Images/Image3.jpg">
<button type="button" onclick="displayPreviousImage()">Previous</button>
<button type="button" onclick="displayNextImage()">Next</button>
<%-- dont write anything lower than this --%>
</div>
</form>
</body>
我试图用这个功能改变代码图像:
setInterval(displayNextImage, 3000);
但是没有用。有什么建议吗?
另外,如何将图像设置为拉伸?
我使用了background-size: cover
但是没有用。有什么建议吗?
答案 0 :(得分:1)
要拉伸图片添加width: 100%;
并自动添加图片,请添加
在javascript中
<script> document.addEventListener("DOMContentLoaded", function(event) { startTimer(); }); </script>
答案 1 :(得分:0)
你必须在html中的body标签的onload上调用该函数,如下所示,
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
document.getElementById("img").alt = "image"+x;
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
document.getElementById("img").alt = "image"+x;
}
function startTimer() {
setInterval(displayNextImage, 5000);
}
var images = [], x = -1;
images[0] = "assets/Images/Image1.jpg";
images[1] = "assets/Images/Image2.jpg";
images[2] = "assets/Images/Image3.jpg";
</script>
</head>
<body onload = "startTimer()">
<form id="form1" runat="server">
<div id="CenterContents" >
<!-- write everything here -->
<img id="img" src="assets/Images/Image3.jpg" alt="image0">
<button type="button" onclick="displayPreviousImage()">Previous</button>
<button type="button" onclick="displayNextImage()">Next</button>
<!-- dont write anything lower than this -->
</div>
</form>
</body>
</html>