简体   繁体   中英

JavaScript don't save style properties

I have a problem with my site. I want to show a div on button click and hide it on another button click so I use JavaScript functions

    function DisplayMessage() {
        var messagebox = document.getElementById("messageConfirmation");
        messagebox.style.display = "block";
    }
    function HideMessage() {
        var messagebox = document.getElementById("messageConfirmation");
        messagebox.style.display = "none";
    }

but when I use them <div> shows and hides in only a moment, and then appears/disappears again, I really don't know what can cause such a problem so i will be really thankful for your answers. Full HTML page code:

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <meta charset="utf-8" />
    <style type="text/css">
        div.wrap {
            width: 850px;
            margin: 0 auto;
        }
        div.messageBox{
            display:none;
            width:500px;
            height:60px;
            background-color: rgb(200, 200, 175);
        }
    </style>
    <script>
        function DisplayMessage() {
            var messagebox = document.getElementById("messageConfirmation");
            messagebox.style.display = "block";
        }
        function HideMessage() {
            var messagebox = document.getElementById("messageConfirmation");
            messagebox.style.display = "none";
        }
    </script>
   </head>
    <body>
    <div class="wrap">
        <div class="messageBox" id="messageConfirmation" >
            <p>Message</p>
            <form>
                <button onclick="HideMessage()">HideME</button>
            </form>
        </div>
        <div>
            <form>
                <button onclick="DisplayMessage()">ShowMe</button>
            </form>
        </div>
    </div>

</body>
</html>

By default, <button> inside a <form> element will act like a submit button, so once your code runs, the form is submitted and the page is refreshed, so it goes back to its old state. Change its type to button in order to achieve what you want:

<button type="button" onclick="HideMessage()">HideME</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM