本文介绍了在JavaScript中使用offsetx和offsettop或在位置x和位置y的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从单击按钮开始的滑块,并且我希望与上一个图像相比,每个图像以200 px的偏移量加载.这是代码:

I have a slider that starts at click on button and I want every image to be loaded at a offset of 200 px in comparison with the previous one. Here is the code:

var image1 = new Image()
image1.src = "img0.jpg"
var image2 = new Image()
image2.src = "img1.jpg"
var image3 = new Image()
image3.src = "img2.jpg"
var image4 = new Image()
image4.src = "img3.jpg"
var image5 = new Image()
image5.src = "img4.jpg"

var step = 1

function slideit() {
    document.images.slide.src = eval("image" + step + ".src")
    if (step < 5)
        step++

    else
        step = 1
    setTimeout("slideit()", 500)

}
<button onclick="slideit()">Try it</button>
<img src="img0.jpg" name="slide" width="100" height="100" position = "absolute">

我想在 JavaScript 中执行此操作,因为我不想在代码中使用 jQuery .

I'd like to do this in JavaScript as I do not want to use jQuery in my code.

推荐答案

嘿,这应该对您有用.我没有时间检查它,所以我希望其中没有错误.只需更新JS,就可以保留html.

Hey this should work for you. I didn't had time to check it, so I hope there are no mistakes in it.Just update the JS, you can leave the html.

致谢

var images = [
    'image1.jpg',
    'Image2.jpg',
    '...'
];

function slideit()
{
    var index = 0;
    var container = document.getElementById('yourContainer');

    var addPic = function()
    {
        var img = document.createElement('img');
        img.src = images[index];
        img.style.position = 'absolute';
        img.style.left = index * 200 + 'px';

        container.appendChild(img);
        index++;
    }


    setInterval(addPic, 1000);
}

这篇关于在JavaScript中使用offsetx和offsettop或在位置x和位置y的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 03:14