<script type="text/javascript">
setInterval(function(){
var change = Array("forimg1","img1");
var r = change[Math.floor(Math.random() * change.length)];
if(r == "forimg1"){
document.getElementById("imagetitle").innerHTML = "Makati Cafe";
}
if(r == "img1"){
document.getElementById("imagetitle").innerHTML = "The Fort Steak House";
}
$("#image_change").attr("src","assets/images/eat/"+r+".jpg");
},2000);
</script>
答案 0 :(得分:0)
我建议使用像:
这样的对象数组,将图像标题与图像URL一起存储var images = [
{title: "Makati Cafe", file: "img1"},
{title: "The Fort Steak House", file: "img2"},
// etc.
]
通过这种方式,您不需要使用if / else结构来确定要显示的标题,您可以使用images[current].title
和images[current].file
从当前对象中选取标题和文件名。< / p>
您也不需要setInterval()
,因为如果您使用jQuery .fadeIn()
和.fadeOut()
函数,他们可以为您控制时间:
$(document).ready(function() {
var images = [
{title: "Makati Cafe", file: "g/200/250"},
{title: "The Fort Steak House", file: "200/250"},
{title: "Whatever", file: "200/350"}
// etc.
];
var $container = $("#container"); // keep references to the container div
var $img = $("#image_change"); // and img and title elements rather than
var $title = $("#image_title"); // looking them up every time we fade
function showNext() {
var current = Math.floor(Math.random() * images.length);
// fade out container, then
$container.delay(1000).fadeOut(500, function() {
// update img src and title text
$img.attr("src", "http://placekitten.com/" + images[current].file);
$title.text(images[current].title);
// fade container in again and then call the showNext() function again
$container.fadeIn(500, showNext);
});
}
showNext();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
<p id="image_title"></p>
<img id="image_change">
</div>
你没有在问题中显示你的HTML,所以我只假设会有一个容器div,其中包含一个img和title元素,然后我就褪了那个容器。显然,您可以修改代码以适合您的实际HTML结构。
(不要担心上面代码中的奇怪文件名,它们只是用于演示目的的库存图片。)