用数组Javascript制作幻灯片 [英] Making a slideshow with arrays Javascript
问题描述
我的目标是制作幻灯片.我这里只有1张图片,打算以后再用.
My goal is to make a slideshow. I have only 1 image here and plan to use more later.
<!DOCTYPE html>
<html onmousedown='event.preventDefault();'>
<head>
<title> Slides </title>
<meta charset='utf-8'>
<style>
table{
margin: 1.5in;
}
.arrow{
color: blue;
cursor: pointer;
}
我试图将图像类别设置为水平和垂直居中的640 x 540像素.我想避免内部填充.不确定是否正确.
I attempted to make the image class 640 x 540 pixels, centered both horizontally and vertically. I want to avoid internal padding. Not sure if it's right.
.img{
height: 540px;
width: 640px;
position: relative;
}
对于图像元素本身,我没有设置任何边距,宽度为100%,具有1像素的实心黑色边框.
For the image element itself I put no margin, is 100% wide, has a 1 pixel solid black border.
#image{
width: 100%;
border: solid 1px;
border-color: black;
}
</style>
<script>
我想制作2个全局变量,即"images"和"imgidx".-images-一个数组,使用images目录中的图像路径作为字符串填充.
I want to make 2 globals, "images" and "imgidx". -images - an array that is filled in with the paths of the images in the images directory as strings.
-imgidx-一个初始设置为0的数字.
-imgidx - a number initially set to 0.
下一步,我要填写以下功能.
Next I want to fill in the following functions.
-递增或递减imgidx.
-Increment or decrement imgidx.
-将img元素上的'src'属性(由ID'img'标识)设置为images [imgidx]处的图像.如果imgidx>图像数组中的图像数,则应换回零.如果它小于零,则应将其设置为小于数组长度的1.
-set the 'src' attribute on the img element (identified by the id 'img') to the image at images[imgidx]. If imgidx is > the number of images in the images array, it should wrap back to zero. If it goes below zero it should be set to 1 less than the length of the array.
function previmg() {
}
function nextimg() {
}
</script>
</head>
<body>
<table>
<tr>
<!-- Clicking on the arrows should change the image being displayed: -->
<td class='arrow' onclick='previmg();'> «
<td class='image'><img id='img' src='https://img-9gag-fun.9cache.com/photo/appxzbM_460s.jpg'>
<td class='arrow' onclick='nextimg();'> »
</table>
</body>
</html>
推荐答案
只需根据要单击的方向更改 img
src,使用图像索引即可确定src应当指向的位置
Just change the img
src based on whichever direction you're clicking, using the image index as to where the src should point to.
var images = ['http://placehold.it/300x150?text=Image1', 'http://placehold.it/300x150?text=Image2', 'http://placehold.it/300x150?text=Image3'];
var index = 0;
var the_image = document.getElementById("main-image");
the_image.src = images[0];
function show_image(direction)
{
if (direction == "left")
{
index--;
}
else
{
index++;
index %= images.length;
}
if (index < 0)
{
index = images.length - 1;
}
the_image.src = images[index];
}
<div>
<button onclick="show_image('left')"><</button>
<button onclick="show_image('right')">></button>
</div>
<div>
<img id="main-image" />
</div>
这篇关于用数组Javascript制作幻灯片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!