JQuery初心者向けフローティングメニュー

画像



この記事は、初心者のjQuery開発者を支援することを目的としています。 私自身は初心者なので、私の経験を私のような人々と共有したいと思います。



私のタスクは、次のクライアントのサイトに「フローティング」メニューを作成することでした。CMSはプロジェクトに最適ではなかったため(Joomla 1.5)、適切な既製のモジュールを見つけてニーズに合わせて調整するのは非常に時間がかかるタスクであるため、独自の「プラグイン」を作成することにしました「(引用符では、結果をプラグインと呼ぶことはほとんどできません)フローティングメニューの場合。



タスクの結果はあまり最適化されておらず、おそらくどこかに非論理的なコードがありますが、独立して開発されたので、初心者が同様のタスクに直面するのを助けるでしょう。



ほぼすべてのシステムに後で組み込むことができるソリューションが作成されました。



この特定の場合のメニューのレイアウトは次のとおりです。

<div id="topMenu"> <div id="activeMenu" style="left: -999px; width: 0px;"></div> <ul> <li><a href="#" class="mainlevel" id="active_menu"> 1</a></li> <li><a href="#" class="mainlevel"> 2</a></li> <li><a href="#" class="mainlevel"> 3</a></li> <li><a href="#" class="mainlevel lastMenuItem"> 4</a></li> </ul> </div>
      
      





実際、activeMenu要素は同じ「フローティング」要素です。 メニューのレイアウトは、jQueryコードの修正を忘れずに、ニーズに合わせて変更できます。



この例のCSS:

 #topMenu{ clear: both; position: relative; overflow: hidden; top: 23px; margin-left: 14px; } #topMenu a{ font-family: Arial; font-size: 12px; font-weight: bold; text-transform: uppercase; color: #686868; text-decoration: none; display: block; float: left; height: 32px; vertical-align: middle; padding-top: 14px; padding-left: 20px; padding-right: 20px; border-left: 1px solid #ccc; z-index: 2; position: relative; } #topMenu a:hover{ text-decoration: none; color: #3d3d3d; } #topMenu a.lastMenuItem{ border-right: 1px solid #ccc; } #activeMenu{ position: absolute; width: 0px; height: 47px; left: -999px; background: #c0c0c0; z-index: 1; }
      
      







実際、jQueryコード自体にはコメントが付いています。

 jQuery(document).ready(function(){ if(jQuery("#active_menu").length>0){ //     ,       var menuWidth = jQuery("#active_menu").outerWidth(); //      var menuLeft = jQuery("#active_menu").position().left; //       jQuery("#activeMenu").stop().animate({ //    left: menuLeft+'px', width: menuWidth+'px' }, 500, 'linear'); } jQuery("#topMenu a.mainlevel").mouseover(function(){ //         .   ,      ,      ,       var menuWidth = jQuery(this).outerWidth(); var menuLeft = jQuery(this).position().left; jQuery("#activeMenu").stop().animate({ left: menuLeft+'px', width: menuWidth+'px' }, 300, 'linear'); }); jQuery("#topMenu").mouseleave(function(){ //           (     ,    ) if(jQuery("#active_menu").length<=0){ //    ,       jQuery("#activeMenu").stop().animate({ left: '-999px', width: '0px' }, 500, 'linear'); } else{ // ,      –     var menuWidth = jQuery("#active_menu").outerWidth(); var menuLeft = jQuery("#active_menu").position().left; jQuery("#activeMenu").stop().animate({ left: menuLeft+'px', width: menuWidth+'px' }, 500, 'linear'); } }); });​
      
      







私は、書かれたコードの理想や寛容さのふりをしません。建設的な批判を喜んでいます。それは私とこの記事を読んだ初心者の両方を助けます。



ここでデモを見ることができます-jsfiddle.net/bYY6Y/7



yurik417からの編集:

そして建設的な批判について:

1.さまざまなイベントでのアニメーションは同じであるため、1つの関数のみを記述し、必要に応じて呼び出す必要があります。

2.同じ要素に常にアクセスしており、DOMを常に検索しています-これは間違っています。 これらの要素を変数にキャッシュします

3.さて、イベントについて読む.on()

jsfiddle.net/bYY6Y/71/




All Articles