3

我在 javascript 中创建了以下幻灯片。但是由于某种原因,在图像的第一张幻灯片中,第一张图像刚刚移动,第二张图像进行了“滑动”。任何帮助,将不胜感激。我已经包含注释以帮助使代码更具可读性。

<!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

您的幻灯片放映在第一个间隔跳过的原因是因为您在第一次创建 Image 对象时没有设置图像的位置;您只是在设置一个名为“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 回答