2015-06-12 49 views
0

在這裏,我打電話給文本和圖像附加到div的JavaScript函數,現在我想在2秒後隱藏div。我怎樣才能做到這一點?如何使用超時隱藏div?

代碼:

function showdiv(city, imagesrc, timeout) { 

    window.setTimeout(function() { 

    document.getElementById('city-order').innerHTML = ""; 
    document.getElementById('order-product').innerHTML = ""; 
    document.getElementById('product-list-display').style.display = "block"; 
    var order_placed_city = document.getElementById('city-order'); 
    var content = document.createTextNode(city); 
    order_placed_city.appendChild(content);  
    var product_order = document.getElementById('order-product'); 
    var elem = document.createElement("img"); 
    product_order.appendChild(elem); 
    elem.src = imagesrc; 

    },timeout); 

    document.getElementById('product-list-display').style.display = "none"; 

} 
+1

'showdiv( '城市',「http://placehold.it/200x200',2000)' - 也許? – TryingToImprove

回答

1

像這樣的東西可能是你在找什麼?

function showdiv(city, imagesrc, timeout) { 

    // Show div 
    document.getElementById('city-order').innerHTML = ""; 
    document.getElementById('order-product').innerHTML = ""; 
    document.getElementById('product-list-display').style.display = "block"; 
    var order_placed_city = document.getElementById('city-order'); 
    var content = document.createTextNode(city); 
    order_placed_city.appendChild(content);  
    var product_order = document.getElementById('order-product'); 
    var elem = document.createElement("img"); 
    product_order.appendChild(elem); 
    elem.src = imagesrc; 

    // Hide div after n milliseconds 
    setTimeout(function() { 
    document.getElementById('product-list-display').style.display = "none";  
    }, timeout); 
} 
2

目前是看代碼,執行以下操作:

showDiv()

  1. 隱藏#product-list-display
  2. timeout -MS追加一些內容

,你可以簡單添加另一個window.setTimeout在隱藏div的時間函數的末尾。

function showdiv(city, imagesrc, timeout) { 

    window.setTimeout(function() { 
    /* ... */ 

    // You could add it here 
    window.setTimeout(hideDiv) 
    },timeout); 

    /* ... */ 

} 

,然後添加其他功能:

function hideDiv() { 
    // Your hiding code here 
} 

我想建議您花點時間看看像例如jQuery的一個框架。這會增加可讀性並使其不那麼複雜。 https://jquery.com

1

使用display:隱藏,如果你只想隱藏元素,顯示無如果您希望它完全消失:

function hideDiv(elementID,timeout) { 
    window.setTimeout(function() { 
     document.getElementById(elementID).style.display = "none"; 
    },timeout); 
}