div をリンクにする

on 2011/09/20 - -

div に a タグと同じ動きをさせたいことは多々ある。

1.js に以下を追加

div の中の a タグの href 属性を取得して、window をそこに遷移する処理、また hover した時に背景色を帰る処理を追加(後者は必須じゃないけど、この方がカッコイイので)。


my.js
$(function(){
     $(".aDiv").click(function(){
         window.location=$(this).find("a").attr("href");
         return false;
    });
});

$(function(){
    $(".aDiv").hover(
	function(){
	    this.style.backgroundColor = "#f9f9ff";
	},
	function(){
	    this.style.backgroundColor = "white";
	}
    );
});



2.css に以下を追加

div にマウスが重なったらカーソルの見た目をポインタにする。


my.css
.aDiv{ cursor: pointer }



3.html を書く

リンクの動きをさせる div を書く。


my.html
<div class="aDiv">
  <a href="http://some.site.url">SomeSite</a>
</div>



以上。

No comments :