簡體   English   中英

使用jQuery顯示/隱藏div?

[英]Show/Hide divs with jQuery?

首先,有許多與我的問題類似的問題,但是我還沒有找到我可以使用的答案。 輸入時,我有一個頁面顯示登錄表單。 我還有一個要隱藏的注冊表。 通過單擊,我希望將登錄表單替換為注冊表單。

我已經嘗試過找到的這段代碼,並且在一點幫助下可以正常工作,它具有很好的平滑過渡,但是從一開始就顯示了這兩個元素。

 $(function() { $('a').click(function() { div = $(this).attr('href'); //grab #one, #two which correspond to the div id we're targeting paragraph = $(div); //store each div in a variable for later use $('#two').hide(); $('div').hide('grey-bg'); //remove any greyed backgrounds $(paragraph).show('grey-bg'); //add grey background to clicked element }); }); 
 a { text-decoration: none; } #one { margin: 10px; padding: 20px; border: 1px solid #000; } #two { margin: 10px; padding: 20px; border: 1px solid #000; } .grey-bg { background-color: #cccccc; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#one">First Link</a><br /> <a href="#two">Second Link</a> <div id="one"> This is the first paragraph. </div> <div id="two"> This is the second paragraph. </div> 

您可以在這里看到它的工作: https : //codepen.io/raazxplorer/pen/rVKzNp

我所做的全部更改為removeClass和toggleClass以隱藏/顯示。

添加display:none; #two

#two {
  margin: 10px;
  padding: 20px;
  border: 1px solid #000;
  display:none;
}

 $(function() { $('a').click(function() { div = $(this).attr('href'); //grab #one, #two which correspond to the div id we're targeting paragraph = $(div); //store each div in a variable for later use $('#two').hide(); $('div').hide('grey-bg'); //remove any greyed backgrounds $(paragraph).show('grey-bg'); //add grey background to clicked element }); }); 
 a { text-decoration: none; } #one { margin: 10px; padding: 20px; border: 1px solid #000; } #two { margin: 10px; padding: 20px; border: 1px solid #000; display:none; } .grey-bg { background-color: #cccccc; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#one">First Link</a><br /> <a href="#two">Second Link</a> <div id="one"> This is the first paragraph. </div> <div id="two"> This is the second paragraph. </div> 

只需在頁面加載時隱藏div之一即可。

您需要的是:

$(document).ready(function(){
    $("#two").hide();
});

進一步了解(document).ready()

我制作了一個JSFiddle ,沒有將(document).ready()放入其中,因為在JSFiddle中沒有必要。

但是您可以將其添加到$("#two").hide();之上$("#two").hide(); 如果你希望。 它也將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM