我正在尝试仅使用Javascript实现滑块(没有像jQuery这样的外部库)。
这是我的HTML文件:
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Latest compiled and minified CSS -->
<script language="javascript" type="text/javascript" src="slider.js"></script>
<link rel="stylesheet" href="stylesheet.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container main-container">
<div id="container">
<img id='slider-img' src='images/img1.png'>
<div id='left_holder'><img onclick="slider(-1)" class='left' src="images/arrow_left.png"></div>
<div id='right_holder'><img onclick="slider(1)" class='right' src="images/arrow_right.png"></div>
</div>
</div>
</body>
</html>
JS滑块文件:
(function() {
slider();
})();
function slider(element) {
var imagecount = 1;
var totalimage = 11;
var image = document.getElementById("slider-img");
imagecount = imagecount + element;
image.src = "images/img" + imagecount + ".png";
}
我在image.src
cannot set property src of null
收到错误,因为document.getElementById("slider-img");
无法获取html代码的元素img
。有人对这个问题有一些了解吗?
答案 0 :(得分:1)
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Latest compiled and minified CSS -->
<script language="javascript" type="text/javascript" src="slider.js"></script>
<link rel="stylesheet" href="stylesheet.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container main-container">
<div id="container">
<img id='slider-img' src='images/img1.png'>
<div id='left_holder'>
<img onclick="slider(-1)" class='left' src="images/arrow_left.png">
</div>
<div id='right_holder'>
<img onclick="slider(1)" class='right' src="images/arrow_right.png">
</div>
</div>
</div>
</body>
</html>
{{1}}
答案 1 :(得分:0)
更改标记,以便在正文结束前加载脚本
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="stylesheet.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container main-container">
<div id="container">
<img id='slider-img' src='images/img1.png'>
<div id='left_holder'><img onclick="slider(-1)" class='left' src="images/arrow_left.png"></div>
<div id='right_holder'><img onclick="slider(1)" class='right' src="images/arrow_right.png"></div>
</div>
</div>
<script language="javascript" type="text/javascript" src="slider.js"></script>
</body>
</html>
所以在执行脚本时会解析所有html
答案 2 :(得分:0)
您可以使用此答案中的document.ready片段:
What is the non-jQuery equivalent of '$(document).ready()'?
在你的情况下:
function slider(element) {
var imagecount = 1;
var totalimage = 11;
var image = document.getElementById("slider-img");
imagecount = imagecount + element;
image.src = "images/img" + imagecount + ".png";
}
document.attachEvent("onreadystatechange", function(){
if (document.readyState === "complete"){
document.detachEvent( "onreadystatechange", arguments.callee );
slider();
}
});