问题
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.
回答1:
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.
回答2:
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);
}
来源:https://stackoverflow.com/questions/21605791/using-offsetx-and-offsettop-in-javascript-or-position-x-and-positon-y