2017-04-23 103 views
-2
<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

添加HTML代碼也.. –

+0

鑑於「jQuery的」標籤,'.fadeOut ()'和'.fadeIn()'?或者這太明顯了? – nnnnnn

+0

這就是爲什麼我要問如何把這個.fadeOut和.fadeIn()在這段代碼中。因爲我是新手在Jquery和Javascript –

回答

0

我建議用圖像的URL一起存儲圖像的標題,通過使用類似對象的數組:

var images = [ 
    {title: "Makati Cafe", file: "img1"}, 
    {title: "The Fort Steak House", file: "img2"}, 
    // etc. 
] 

這樣,你不需要if/else結構來確定要顯示的標題,您可以從當前對象中選取標題和文件名,其中images[current].titleimages[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結構。

(不要擔心在上面的代碼中的怪異的文件名,他們只是庫存圖片用於演示目的。)