How to 'open' Bootstrap Dropdown menus on pageload on screens smaller than 600px

限于喜欢 提交于 2019-12-10 20:15:46

问题


im trying to get my bootstrap dropdowns to be open by default at screens at or smaller than 600px (mobile).

this seems to get it to try but it looks like something overrides it and closes it again:

<script type="text/javascript">
$(window).load(function () {
    var width = $(window).width();
    if (width >= 0 && width <= 600) {
        $('#openBrowseMobile').addClass('open');
    }
    else {
        $('#openBrowseMobile').removeClass('open');
    }
})
.load();
</script>

any ideas on how to make this work?

I can get it to work on resize with this, but i need it to work on pageload/doc ready..

<script type="text/javascript">
$(window).resize(function () {
    console.log('resize called');
    var width = $(window).width();
    if (width >= 0 && width <= 600) {
        $('#openBrowseMobile').addClass('open');
    }
    else {
        $('#openBrowseMobile').removeClass('open');
    }
})
.resize();
</script>

回答1:


You can move them into the same handler, by triggering on multiple events.

<script type="text/javascript">
$(window).on('load resize',function () {
    console.log('resize called');
    var width = $(window).width();
    if (width >= 0 && width <= 600) {
        $('#openBrowseMobile').addClass('open');
    }
    else {
        $('#openBrowseMobile').removeClass('open');
    }
});
</script>



回答2:


I had the same issue, here is another approach using jquery that doesn't involve messing with less code or css.

I just added a trigger to open the dropdown menu inmediately after menu is opened.

There's a timeout that waits until the main menu is opened. (there will be 100 ms delay until dropdown is opened), If you like it to don't wait I guess that can be changed in less.

$(".navbar-toggle").click(function() {         

    if (window.matchMedia("(max-width: 768px)").matches) {
        // on mobile, dropdown default opened:
        setTimeout(function() {
            $(".dropdown-toggle").click();
        }, 100);

    }
});


来源:https://stackoverflow.com/questions/19082741/how-to-open-bootstrap-dropdown-menus-on-pageload-on-screens-smaller-than-600px

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!