循环通过图像和文本

时间:2015-05-04 23:32:39

标签: javascript html

我试图让它让页面循环显示4张不同的图片,只显示1张以及上面的文字,每张图片都会更改。我设法让图像循环,但不知道我是怎么做文本的。这是我到目前为止所得到的。

<!DOCTYPE html>
<html>
<head>
<title> banner array thing </title>

<script>
var names = ["name1", "name2", "name3", "name4"];
var description = [4];
var imgArray = new Array(4);
var index = 0;

function cycle()
{

document.banner.src = imgArray[index].src;
index++
if (index > 3)
{
index = 0;
}
setTimeout("cycle()", 2000)
return;
}

function startup()
{
 imgArray[0] = new Image;
 imgArray[0].src = "img1.jpg";

 imgArray[1] = new Image;
 imgArray[1].src = "img2.jpg";

 imgArray[2] = new Image;
 imgArray[2].src = "img3.jpg";

 imgArray[3] = new Image;
 imgArray[3].src = "img4.jpg";

 cycle();
 return;
}
</script>

<link rel="stylesheet" type="text/css" href="main.css">
</head>

<body onLoad="startup()">
<div align="center">
</br> </br>

<!-- Where'd I'd like the changable text-->

<img name="banner" src="img1.jpg">

 </div>
</body>
</html>

就像我说的,图像循环工作,我只想要一些文本随图像改变。请提前帮助和感谢。希望我措辞一切正确,这样你才能理解。

2 个答案:

答案 0 :(得分:0)

您应该将JavaScript与HTML分开,以便将其存储到缓存中。你想要的就像:

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <style type='text/css'>
      @import 'main.css';
    </style>
    <script type='text/javascript' src='main.js'></script>
  </head>
<body>
  <img id='banner' src='img1.jpg' />
</body>
</html>

<强> main.js

//<![CDATA[
var pre = onload;
onload = function(){
if(pre)pre();
var doc = document, bod = doc.body;
function E(e){
  return doc.getElementById(e);
}
function imgRot(where, startNum, finishNum, prefix, ext, interval){
  var n = startNum, x = ext.replace(/^\./, '')+'.';
  setInterval(function(){
    n++; where.src = prefix+n+x;
    if(n === finishNum)n = startNum-1;
  }, interval);
}
imgRot(E('banner'), 1, 4, 'img', 'jpg', 2000);
}
//]]>

答案 1 :(得分:-1)

<div id = "yourText"></div>

将它放在你的标记中,然后:

function cycle()
{

document.banner.src = imgArray[index].src;
document.getElementById("yourText").innerHTML = names[index];
index++
if (index > 3)
{
index = 0;
}
setTimeout("cycle()", 2000)
return;
}