如何添加渐变效果这个JavaScript随机图像
问题描述:
<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>
答
我建议用图像的URL一起存储图像的标题,通过使用类似对象的数组:
var images = [
{title: "Makati Cafe", file: "img1"},
{title: "The Fort Steak House", file: "img2"},
// etc.
]
这样,你不需要if/else结构来确定要显示的标题,您可以从当前对象中选取标题和文件名,其中images[current].title
和images[current].file
。
你也并不真的需要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结构。
(不要担心在上面的代码中的怪异的文件名,他们只是库存图片用于演示目的。)
添加HTML代码也.. –
鉴于“jQuery的”标签,'.fadeOut ()'和'.fadeIn()'?或者这太明显了? – nnnnnn
这就是为什么我要问如何把这个.fadeOut和.fadeIn()在这段代码中。因为我是新手在Jquery和Javascript –