[英]I can't get my image slideshow to work using JavaScript
我正在嘗試使用下面的Javascript代碼創建一個簡單的圖像幻燈片類型的東西,但是它的作用是在網頁中顯示所有其他內容的第一個圖像,然后在5秒鍾后清除頁面並顯示相同的圖像,然后再次5秒,除了它不再清除頁面。
JavaScript:
var waiPics=new Array();
waiPics[0]='images/path.jpg';
waiPics[1]='images/gorse.jpg';
waiPics[2]='images/stream.jpg';
waiPics[3]='images/pines.jpg';
waiPics[4]='images/stump.jpg';
var time;
function timeUp() {
delete document.write();
nextPic();
}
function nextPic() {
var picNum=0;
if (picNum = waiPics.length) {
picNum=0;
}
else {
picNum++;
}
document.write('<img src="'+waiPics[picNum]+'" title="Waipahihi" alt="Waipahihi">');
time=setTimeout("timeUp()",5000);
}
HTML:
<script type="text/javascript">
<!-- Begin
nextPic();
// End -->
</script>
我對Java語言不是很有經驗,因此在此先感謝您的幫助。
picNum始終為零,因為它是在函數內部聲明的,並且每次調用該函數時都將設置為零。 即使您解決了這個問題,您的條件也是錯誤的:
if (picNum = waiPics.length) {
條件應為:
if (picNum === waiPics.length) {
單個=符號將長度分配給picNum,然后轉換為布爾值。 數組長度為非零,因此它成為真實值。 然后每次重置為零。
考慮使用JSLint來檢查代碼中的錯誤並提出改進建議。 它標記了問題:
"Expected a conditional expression and instead saw an assignment."
if (picNum = waiPics.length) {
實際上,在您的代碼上使用JSLint並檢查了其建議之后,我將使用更多類似的內容:
// New array creation syntax
var waiPics = ['images/path.jpg', 'images/gorse.jpg', 'images/stream.jpg', 'images/pines.jpg', 'images/stump.jpg'];
var picNum = 0; // Declare outside inner function so its value is preserved
var myDiv = document.getElementById("ssdiv"); // Get a div element to insert picture into
function nextPic() {
if (picNum === waiPics.length) { // Proper comparison
picNum = 0;
} else {
picNum += 1;
}
// Set picture into div element without evil document.write
myDiv.innerHTML = '<img src="' + waiPics[picNum] + '" title="Waipahihi" alt="Waipahihi">';
// No longer need timeUp; also don't use eval syntax
setTimeout(nextPic, 5000);
}
分配innerHTML可以避免document.write的各種問題,也不需要刷新頁面即可更改幻燈片圖像。 另請注意其他注釋。
您需要在此處使用比較運算符('==')而不是分配('='):
//if (picNum = waiPics.length) {
if (picNum == waiPics.length) {
看這個例子...
http://jsfiddle.net/DaveAlger/eNxuJ/1/
slides.html
您自己的幻燈片顯示正常工作,請將以下html復制並粘貼到任何文本文件中,並將其另存為slides.html
您可以在<div class="slideshow">
添加任意數量的<img>
元素
請享用!
<html>
<body>
<div class="slideshow">
<img src="http://davealger.info/i/1.jpg" />
<img src="http://davealger.info/i/2.bmp" />
<img src="http://davealger.info/i/3.png" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
</script>
<style>
.slideshow { position:relative; }
.slideshow img { position:absolute; left:0; top:0; }
</style>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.