简体   繁体   English

创建一个下拉菜单,该菜单在页面顶部向上打开,向下滚动时向下滚动

[英]Creating a drop-down menu that opens upward at the top of the page and then downward when scrolled down

I'm trying to create a drop-down menu that opens upward only when the window is at the very top and then open downwards when its not. 我正在尝试创建一个下拉菜单,该菜单仅在窗口位于最顶部时才向上打开,而当窗口不在顶部时才向下打开。 I'm trying to achieve this with an IF-Statement but cannot get it to display downwards.'show' will display the menu upwards and 'show2'will display it downwards. 我正在尝试使用IF语句来实现这一点,但是无法使其向下显示.'show'将向上显示菜单,而'show2'将向下显示它。

This is the CSS for the "show" and "show2". 这是“ show”和“ show2”的CSS。

.show {display:block;
        bottom: 100%;
}
.show2 {display:block;

}

This is the JQuery script. 这是JQuery脚本。 As you can see, I'm trying to have it toggle with 'show' when its at the very top of the page and I'd like it to change to 'show2' when the user scroll down from the top by 1 or 2 px's. 如您所见,我试图在页面顶部将其切换为“ show”,并希望当用户从顶部向下滚动1或2时将其更改为“ show2” px的。 aka straight away. 又名立即。

When the user clicks on the dropdown button,toggle between hiding and showing the dropdown content. 当用户单击下拉按钮时,在隐藏和显示下拉内容之间切换。

if (window.top == window.self) {
    function myFunction() {
        document.getElementById("myDropdown").classList.toggle("show");
    }
} else {
    function myFunction2() {
        document.getElementById("myDropdown").classList.toggle("show2");
    }
}

Close the dropdown if the user clicks outside of it 如果用户单击下拉列表,请关闭它

window.onclick = function (event) {
    if (!event.target.matches('.dropbtn')) {

        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i--) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            } else(openDropdown.classList.contains('show2')) {
                openDropdown.classList.remove('show2');
            }
        }
    }
}

Any help is welcome and thank you in advance! 欢迎任何帮助,并预先感谢您!

According to this question, you can conditionally declare functions as follows. 根据问题,您可以有条件地声明函数,如下所示。

var myFunction;
if (window.top == window.self) {
    myFunction = function () {
        document.getElementById("myDropdown").classList.toggle("show");
    };
} else {
    myFunction = function () {
        document.getElementById("myDropdown").classList.toggle("show2");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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