![](/img/trans.png)
[英]How can I show / hide a div using the properties from a CSS file using JavaScript
[英]How can I hide a DIV without using CSS?
我想在頁面加載時隱藏DIV,但由於某些頁面限制而無法使用CSS。
如何使用Javascript或其他方法隱藏DIV? 我想在頁面加載時隱藏DIV,而無需用戶按下按鈕。
干杯。
window.onload = function(){
document.getElementById('your_div_id').style.display = 'none';
}
或者,在jQuery中:
$(document).ready(function(){
$('#your_div_id_or_other_selector').hide();
});
document.getElementById("yourDivId").style.display = "none";
這會將CSS display
屬性設置為none
,這將隱藏該元素,並刪除該元素在DOM中占用的任何空間。
您可以在onload
函數中運行此代碼,因此它在頁面加載時運行:
window.onload = function() {
document.getElementById("yourDivId").style.display = "none";
}
如果要隱藏元素,但在DOM中保留它的空間,則可以使用visibility = "hidden"
代替display = "none"
。
只需將hidden="true"
添加到HTML標記即可。
使用jQuery:
$("#div_id").hide();
再次顯示:
$("#div_id").show();
在常規javascript中:
# retains the hidden div's position
`document.getElementById('div_id').style.visibility = 'hidden';`
# collapses the hidden div's positioning
`document.getElementById('div_id').style.display = 'none';`
假設您可以使用一些框架來簡化操作,並且選擇jQuery,則有三個選項(請參閱jsfiddle ):
jQuery('#mydiv1').hide(); // bases on CSS, as other answers
jQuery('#mydiv2').remove();
jQuery('#mydiv3').detach();
由於您明確要求不提供基於CSS的解決方案 ,因此第一個實際上是您不想使用的東西。 第二個刪除所有事件等的div,第三個刪除不刪除事件的div(因此您應該能夠在需要時再次添加它)。
有關詳細信息,請參閱api.jquery.com上的jQuery文檔。
有幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.