簡體   English   中英

隱藏顯示並支持html5

[英]hide show with support of html5

我需要協助。 當我單擊THIS IS 1和THIS IS 2時,輸入框出現了。 我想單擊“此為1”並將輸入框帶至“此IS 1”,而不單擊“此2”,仍將輸入框帶至“此IS 1”。因此,當我單擊“此為1”時,我想輸入的框位於“此IS 1”的下方。 IS 2輸入框位於IS 2的下方

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>

    </head>

    <body>
    <span onclick="MFunction()">THIS IS 1</span>
    <p></p>
    <span onclick="MFunction()">THIS IS 2</span>
    <div id="showhide" style="display:none;">
                        <input type="text"  required>
                        <br></br>
                    <button  class="btn btn-md-2 btn-primary">submit</button> 
                    </div>
    <script>
    function MFunction() {
        var x = document.getElementById("showhide");
        if (x.style.display === "none") {
            x.style.display = "block";
        } else {
            x.style.display = "none";
        }
    }
    </script>
    </body>
    </html>

如果要使用相同的showhide div在clicked元素下顯示,則可能需要在單擊時使用insertBefore

請參見下面的代碼段:

 function MFunction(event) { var x = document.getElementById("showhide"); if (x.style.display === "none") { x.style.display = "block"; } x.parentNode.insertBefore(x, event.target.nextSibling); } document.addEventListener('click', function(event){ if(event.target.className.includes("thisis")){ MFunction(event); } }); //document.getElementById("thisis1").addEventListener("click", MFunction); //document.getElementById("thisis2").addEventListener("click", MFunction); 
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <span id="thisis1" class="thisis">THIS IS 1</span> <p></p> <span id="thisis2" class="thisis">THIS IS 2</span> <p></p> <span id="thisis3" class="donotshow">DO NOT SHOW ON THIS IS</span> <div id="showhide" style="display:none;"> <input type="text" required> <br><br> <button class="btn btn-md-2 btn-primary">submit</button> </div> </body> 

您也可以在這里進行測試

更新1:

我已經更新了答案,可以為多個元素添加單擊事件。 你可以在這里測試

暫無
暫無

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

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