MAC風DOCメニューをjQueryで作るチュートリアル

Javascript

2010.03.03

MAC風DOCメニューをjQueryのanimateを使えば簡単に実装できるであろうと思い作成したのですが、なかなか大変でした。

HTMLソース

[sourcecode language=’html’]

  • Photoshop
  • Illustrator
  • Dreamweaber
  • Fireworks
  • Flash

[/sourcecode]

注意点(width属性とheight属性の指定)

このimg要素にはすべてwidth属性とheight属性を明記しています。
その理由としては、JavaScriptでwidth();とheight();と値を取得する際に、読み込み速度等できっちり値を取得してくれない場合があるためです。
さらにsafariでは、img要素にwidth属性とheight属性を指定しないと、JavaScriptでは値を取得してくれません。
ですので、widthとheightの値はを明記しているのです。

Javascriptソース

[sourcecode language=’javascript’]
$(function(){
var DOC = “#doc”;
$(“li” , DOC).each(function(){
var imgWidth =$(“img” , this).width();
var imgHeight =$(“img” , this).height();

$(this).css({“position”: “relative”, “width”: imgWidth + “px”, “height”: imgHeight + “px”});
$(“a” , this).css({“display”: “block”});
$(“img” , this).css({“width”: imgWidth + “px”, “height”: imgHeight + “px”});

$(this).hover(function(){
$(“img” , DOC).css({“zIndex”: “1”});
$(“img” , this).css({“position”: “absolute”, “zIndex”: “100”});
$(“img” , this).stop().animate({
“top”: “-” + imgHeight / 2 + “px”,
“left”: “-” + imgWidth / 2 + “px”,
“width”: imgWidth * 2 + “px”,
“height”: imgHeight * 2 + “px”
}, 300);
}, function(){
$(this).css({“width”: imgWidth + “px”, “height”: imgHeight + “px”});
$(“img” , this).stop().animate({
“top”: 0,
“left”: 0,
“width”: imgWidth + “px”,
“height”: imgHeight + “px”
}, 300);
});

});
});
[/sourcecode]

Javascriptの解説

4-9行目:変数と初期設定
4-5行目の変数で画像の幅、高さを取得します。
次にcssの設定をします。Javascriptで指定することで、どんな幅、高さの画像でも対応できるようにしています。
11-28行目:ホバー設定
12-13行目でz-indexを全て1にし、ホバーした要素のz-indexを100にしています。
14-19行目にanimate設定が記述されています。
ここでポイントとなるのが、top、leftの値に「-」が付いていることです。
画像を2倍にするのは「*2」で実現できますが、それだけですと、左上が基点となり大きくなります。
そのため、画像サイズの半分だけマイナスに移動させれば、真ん中から拡大しているようになります。

サンプル

サンプルはこちらになります

  1. Web-Parkのホーム > 
  2. Javascript > 
  3. MAC風DOCメニューをjQueryで作るチュートリアル
オススメ本(既読)
読んでみたい本(未読)

COMMENT PLEASE!!

about me

Manabu Kushimoto

Welcome to WEB-PARK.ORG!!
This domain was made since 2008 February.

Gender
Male
Birth year
1982
From
Osaka,Japan
  • はてな?ブックマーク
  • delicious
  • facebook