簡體   English   中英

如何僅使用javascript和css隱藏和顯示表單內的div

[英]how to hide and show a div that is inside of a form using only javascript and css

我有一個窗體,其中包含多個div,將某些輸入字段組合在一起。 我想在頁面初始加載時隱藏其中一些div(以及這些div中的輸入字段)。 這對於CSS的display:none屬性很簡單。 然后,我想在用戶單擊“顯示/隱藏”按鈕時顯示那些隱藏的div及其輸入字段。 我為此項目僅使用javascript和CSS(無jquery)。

我有一個基本的javascript函數,只需單擊一下按鈕,即可交替隱藏(display:none)或顯示(display:block)div。 當我在div不屬於表單的測試頁上使用該函數時,該函數運行良好。 但是,當我嘗試對表單的divs部分(即內部)使用相同的功能時,它不起作用。 實際上,它似乎可以工作,但隨后幾乎立即恢復為顯示設置的初始狀態。 我感覺問題出在我的div位於表單內這一事實,但是我不明白為什么這會是一個問題。 我該怎么做才能更正此問題,以便表單內的div可以通過按鈕的切換隱藏/顯示。

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
#random {
    width: 600px;
    min-height: 50px;
    background-color:#E01418;
    color:#B5F0B9;
    display: block;
}
#hideshow {
    width: 600px;
    min-height: 50px;
    background-color:#223FCD;
    color:#F2D595;
    display:block;
}
</style>
</head>

<body>

<form id="myform" name="myform" method="post" action="">
    <div id="random">
        <input type="text" id="firstname" name="firstname" placeholder="firstname">
        <input type="text" id="lastname" name="lastname" placeholder="lastname">
        <input type="email" id="email" name="email" placeholder="email">
    </div>

    <div id="hideshow">
        <input type="password" id="password" name="password" placeholder="password">
        <input type="text" id="address" name="address" placeholder="address">
        <input type="text" id="phone" name="phone" placeholder="phone">
    </div>
    <input type="submit" id="submit" name="submit" value="Update">
    <button id="togglehideshow">Hide/Show</button>
</form>

<script>

var button = document.getElementById('togglehideshow'); 

button.onclick = function() {
    var div = document.getElementById('hideshow');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

</script>

</body>

</html>

最后一件事-我正在使用的按鈕不是表單的提交按鈕。 我只是不想讓任何人對此感到困惑。 謝謝您的幫助!

為顯示和隱藏div的按鈕添加type = button。

<button type="button" id="togglehideshow">Hide/Show</button>

這是因為按鈕在隱藏div之后嘗試提交表單。

暫無
暫無

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

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