// HTML當我使用純JavaScript來製作滑塊時,無法使autoslider()正常工作?
<div class="sliderImage">
<img src="icon-facebook.png" name="slidershow" />
</div>
<table>
<tr>
<td align="left">
<a href="" class="sliderPrevious">Previous</a>
</td>
<td align="right">
<a href="" class="sliderNext">Next</a>
</td>
</tr>
</table>
<div id="description">
</div>
// JavaScript的
<script type="text/javascript">
(function(){
var Image = new Array('icon-facebook.png','icon-google.png','icon-mail.png','icon-twitter.png');
var Description = new Array('This is an facebook icon','This is an google icon','This is an mail icon','This is an twitter icon');
var sliderPrevious = document.getElementsByClassName('sliderPrevious')[0];
var sliderNext = document.getElementsByClassName('sliderNext')[0];
var sliderAuto = document.getElementsByClassName('sliderAuto')[0];
var myAutoSlider;
var Image_Number = 0;
var Image_Length = Image.length - 1;
function change_image(num){
Image_Number = Image_Number + num;
if(Image_Number > Image_Length){
Image_Number = 0;
}
if(Image_Number < 0){
Image_Number = Image_Length;
}
document.slidershow.src = Image[Image_Number];
document.getElementById('description').innerHTML = Description[Image_Number];
return false;
};
function autoSlider(){
myAutoSlider = setInterval(change_image(1), 1000);
};
function myEventLisener(target, event, myNumber){
target.addEventListener(event, function(e){
e.preventDefault();
change_image(myNumber);
clearInterval(myAutoSlider);//if click ,then stop autoplay
});
};
autoSlider();
myEventLisener(sliderPrevious,'click', -1);
myEventLisener(sliderNext,'click', 1);
}());
</script>
以上是我寫的,使使用純JS滑塊的代碼。使用上面的代碼,我可以使用下一個和預覽按鈕,但我不能讓它自動播放,這是autoSlider函數的設置。
我試過檢查員,但沒有顯示任何問題。一切都好,但autoSlider()不能運行,我不知道爲什麼?提前幫助?Thannks。
除了問題,welccome指出我的代碼的壞點,CZ我正在學習JavaScript的幾個月。並需要您的專業意見。 –
首先我想可能myAutoSlider變量不能被訪問,因爲函數範圍和我設計myAutoSlider全局而不是myAutoSlider函數,但它似乎沒有工作,請幫助。我花了半天... –