2012-01-09 11 views
0

私は画面サイズが一定の幅を下回ったときに "More .."メニューアイテムを動的に作成するレスポンシブなナビゲーションメニューを開発しようとしています。 HERESに私のコード今のところJavascriptベースのメディアクエリ

HTML:

<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を:

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()機能を実行すると、それは実際にすべてのウィンドウをリサイズのためのMoreMenu()関数を実行しています活動は800px未満です - これは理想的ではありません。

したがって、画面サイズが800を下回ったときにそのMoreMenu()関数を実行する方法はありますか?

だけMoreMenuを呼び出すように、幅がresizeイベントハンドラに以前何であったかを追跡するJavaScript :)

答えて

2

まわりで私の頭を取得するために-Struggling事前に感謝してRemoveMoreMenuときパス幅制限が上下します。

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を実行したい場合があります。

関連する問題