我正在学习javascript。我已经制作了一个图像滑块,但想要为每张幻灯片添加文字我有5张图片只想将文字添加到每张幻灯片中,它位于中间,从上到下居中。谢谢你们
var i = 0;
var images = [];
var time = 3250;
// Image List
images[0] = 'http://lorempixel.com/300/200';
images[1] = 'http://placehold.it/300x200';
images[2] = 'http://lorempixel.com/300/200';
images[3] = 'http://placehold.it/300x200';
images[4] = 'http://lorempixel.com/300/200';
// Change Image
function changeImg(){
document.slide.src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
&#13;
* {margin:0;padding:0;box-sizing:border-box}
#wrapper {
width: 800px;
height: 400px;
margin: 50px auto;
}
&#13;
<h1>JS Slider </h1>
<div id="wrapper">
<img name="slide" alt="slide image">
</div>
&#13;
答案 0 :(得分:0)
为了显示每张图片的唯一文本,首先必须实现一个包含这两个值的对象:
var images = [];
function appendImage(src, text) {
images.push({
src: src,
text: text
});
}
然后像这样创建你的5张图片:
appendImage('1.jpg', 'Picture 1');
appendImage('2.jpg', 'Picture 2');
appendImage('3.jpg', 'Picture 3');
appendImage('4.jpg', 'Picture 4');
appendImage('5.jpg', 'Picture 5');
只需确保您有一个元素(使用CSS)填充文字
<div id="wrapper">
<img name="slide" alt="slide image">
<span id="sliderText"></span>
</div>
对changeImg
函数的更改很小,您只需要考虑新的数据结构。
var sliderText = document.getElementById('sliderText');
function changeImg(){
document.slide.src = images[i].src;
sliderText.innerHTML = images[i].text;
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
答案 1 :(得分:0)
您可以使用javascript对象:
var i = 0;
var images = [];
var time = 3250;
// Image List
images[0] = {
url: 'http://via.placeholder.com/120x120',
caption: '120x120'
};
images[1] = {
url: 'http://via.placeholder.com/130x130',
caption: '130x130'
};
images[2] = {
url: 'http://via.placeholder.com/140x140',
caption: '140x140'
};
images[3] = {
url: 'http://via.placeholder.com/150x150',
caption: '150x150'
};
images[4] = {
url: 'http://via.placeholder.com/160x160',
caption: '160x160'
};
// Change Image
function changeImg() {
document.slide.src = images[i].url;
caption.innerText = images[i].caption;
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("changeImg()", time);
}
window.onload = changeImg;
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#wrapper {
width: 800px;
height: 400px;
margin: 50px auto;
}
<h1>JS Slider </h1>
<div id="wrapper">
<img name="slide" alt="slide image">
<div id="caption">2134234</div>
</div>