简体   繁体   中英

JS Toggle Menu acts as back to top button?

I have a toggle menu button that uses JS to toggle on/off. Just until recently I've noticed that it acts as a back to top function as well if I toggle on the menu while away from the top of the page, it instantly brings me to the top of the page. Not sure exactly why it is as I am a total JS noob. Would much appreciate if anyone could help out with this.

    <!--HTML MARKUP-->
    <header class="menu">
        <a href="#" onclick="toggle_visibility('drop-menu-content');">
            <div id="drop-menu">
                <i class="fa fa-bars"></i>
            </div>
        </a>
            <ul id="drop-menu-content">
            </ul> 
    </header>

    <!--Javascript Below-->
    <script>
    function toggle_visibility(id) {
        var e = document.getElementById(id);
        if(e.style.display == 'block')
        e.style.display = 'none';
        else
        e.style.display = 'block';
    }
    </script>

Thanks !

这里没有链接,所以用<button>替换<a>并摆脱href="#"

The default behavior for hash urls in a tags is to scroll the browser window to the element on the page whos id is specified by the hash. For example, if you had an element with an id of "my-element", click an a element with href="#my-element" will scroll the browser window to that element. If the has url is just the hash the browser interprets this as the top of the page.

In order to prevent this you can either take @danielnixon's advice and replace the a with a button, you can remove the href attribute entirely and then re-style the element to have pointer: cursor since non-link a tags have the default cursor, or you can update your click event handler to use a function which looks like the following:

function toggleMenu(ev) {
    ev.preventDefault();
    toggle_visibility('drop-menu-content');
}

Calling preventDefault() prevents the browser from executing its default behavior on the event, which in this case is to scroll the window to the top of the document.

Edit: don't remove the href attribute if you are going to use an a element. Thanks, @danielnixon

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