3

次のスライドショーをjavascriptで作成しました。しかし、何らかの理由で、画像の最初のスライドスルーで、最初の画像が移動し、2番目の画像が「スライド」します。どんな助けでもいただければ幸いです。コードを読みやすくするためにコメントを含めました。

<!DOCTYPE html>

<html>

<head>

<title></title>
<style type="text/css">
img.pic {
    position: absolute;
    height: 768px;
    width: 1024px;
}
html, body { 
    background-color:#3b3b35;
    width: 1024px;
    height: 768px;
    margin: 0;
    padding: 0;
    overflow:hidden;
}
</style>

</head> 

<body onload="startImages()">

<img class="pic" id="slide0" src="1.jpg" alt="pic1" />
<img class="pic" id="slide1" src="2.jpg" alt="pic2" />
<img class="pic" id="slide2" src="3.jpg" alt="pic3" />
<img class="pic" id="slide3" src="4.jpg" alt="pic4" />
<img class="pic" id="slide4" src="5.jpg" alt="pic5" />
<img class="pic" id="slide5" src="6.jpg" alt="pic6" />
<img class="pic" id="slide6" src="7.jpg" alt="pic7" />
<img class="pic" id="slide7" src="8.jpg" alt="pic8" />
<img class="pic" id="slide8" src="9.jpg" alt="pic9" />
<img class="pic" id="slide9" src="10.jpg" alt="pic10" />
<script type="text/javascript">
// Define the x start variable
var xstart = 0;

// Constructor for an image object:
function Image(obj, x) {
    this.object = obj;
    this.xpos = x;
}

// Image array
var Images = [];

// Sets up the images
function startImages() {
    for (var Imageamount = 0; Imageamount < 10; Imageamount++) {
        var Imgstore = document.getElementById("slide" + Imageamount);

        // Puts image in the array
        Images[Imageamount] = new Image(Imgstore, xstart);
        xstart = xstart - 1024;
    }
    // Controlls the delays
    setInterval(function () {
        var val = 0;
        var Interval = setInterval(function () {
            imSlide();
            val++;
            if (val == 16) clearInterval(Interval); // 16*64 = 1024, ie image size
        }, 30);
    }, 5000);
}

function imSlide() { // Controlls sliding
    for (var Slide = 0; Slide < Images.length; Slide++) {
        var image = Images[Slide];
        // Update + 64 to give a smooth slide. Updates 16 times so 16*64=1024

        var x = image.xpos + 64;
        // Move image from far right back to front of image stack
        if (x == 5120) {

            x = -5120;

        }
        // Store position back in array
        image.xpos = x;
        // Move the image
        image.object.style.left = x + "px";
    }
}

</script>

</body>
</html>
4

1 に答える 1

2

スライドショーが最初の間隔でスキップする理由は、最初に画像オブジェクトを作成するときに画像の位置を設定していないためです。'xpos'という名前の変数のみを設定しています。これにより、すべての画像が互いに重なり合い、ページの読み込み時に最後の画像#slide9が他の画像の上に表示されます。

Imageオブジェクト宣言を次のように変更します。

function Image(obj, x) {
    this.object = obj;
    this.xpos = x;
    this.object.style.left = x + "px"; //<--- this is the new part
}

これがjsfiddleです:http://jsfiddle.net/w9qQx/4/

于 2012-12-03T05:47:54.487 に答える