Using offsetx and offsettop in JavaScript or posit

2019-08-27 22:36发布

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

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

2条回答
我只想做你的唯一
2楼-- · 2019-08-27 22:50

I actually don't get whats your question. Maybe you should be a bit more precise. If you want to make a picture slider, then your approach doesn't seems to be right.

查看更多
萌系小妹纸
3楼-- · 2019-08-27 23:00

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.

Regards

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);
}
查看更多
登录 后发表回答