首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于Javascript的媒体查询

基于Javascript的媒体查询
EN

Stack Overflow用户
提问于 2012-01-09 18:35:49
回答 1查看 215关注 0票数 0

我正在尝试开发一个响应式导航菜单,它可以动态地创建一个“更多..”当屏幕尺寸低于特定宽度时显示菜单项。

到目前为止,我的代码如下:

Html:

代码语言:javascript
复制
<ul id="menuElem" class="clearfix">
    <li class="HighLighted"><a href="#">Menu Item 1</a></li>
    <li><a href="#">Menu Item 2</a></li>
    <li><a href="#">Menu Item 3</a></li>
    <li><a href="#">Menu Item 4</a></li>
    <li><a href="#">Menu Item 5</a></li>
    <li><a href="#">Menu Item 6</a></li>
</ul>

Javascript:

代码语言:javascript
复制
function MoreMenu () {
    //Checks if sub-menu exsists
    if ($(".sub-menu").length > 0) {
        //if it does then prepends second-last menu item to sub menu
        $(".sub-menu").prepend($("#menuElem > li:nth-last-child(2)"));
    }
    else {
        //if it doesn't exsist then appends a list item with a menu-item "more" having a sub-menu and then prepends second-last menu item to this sub menu.
        $("#menuElem").append("<li class='more'><a href='#'>More...</a><ul class='sub-menu'></ul></li>");
        $(".sub-menu").prepend($("#menuElem > li:nth-last-child(2)"));
    }
}

function RemoveMoreMenu () {
    //checks if sub-menu has something
    if ($(".sub-menu li").length > 0) {
        //if it does then the first child is taken out from the sub-menu and added back to the main menu.   
        $(".sub-menu li:first-child").insertBefore($("#menuElem > li:last-child"));

        //if sub-menu doesn't have any more children then it removes the "more" menu item.
        if ($(".sub-menu li").length === 0) {
            $(".more").remove();
        }   
    }
}

function Resize() {
    benchmark = 800; //Maximum width required to run the function
    $(window).resize((function() {
        currentWidth = $(window).width(); //Current browser width
        if (benchmark - currentWidth > 0) { 
            //checks if the browser width is less than maximum width required and if true it trigers the MoreMenu function              
            MoreMenu ();
            console.log("screen size resized down");
        } 
        else {
        }
    }));
}

问题是,当我运行Resize()函数时,它实际上会为每个小于800px的窗口调整活动运行MoreMenu()函数-这是不理想的。

那么,有没有办法在屏幕尺寸低于800时只运行一次MoreMenu()函数呢?

提前感谢-Struggling让我明白了javascript :)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-09 20:54:45

跟踪resize事件处理程序之前的宽度,以便只在传递宽度限制时调用MoreMenuRemoveMoreMenu

代码语言:javascript
复制
var previousWidth = $(window).width();
var benchmark = 800;

$(window).resize(function() {
    var newWidth = $(window).width();
    if (newWidth < benchmark && previousWidth >= benchmark) {
        MoreMenu();
    }
    else if (newWidth >= benchmark && previousWidth < benchmark) {
        RemoveMoreMenu();
    }
    previousWidth = newWidth;
});

如果previousWidth从一开始就低于基准测试,那么您可能还希望在开始时运行MoreMenu

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8787070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档