もくじ(実装サンプル)
1.【サンプル】まるでクリッカブルしてみた
クローム(chrome)では、画像のwidthとheightを指定しないとクリッカブルしてくれないので要注意です。(2020年8月現在)
See the Pen
【jQuery】画像のレスポンシブ対応でクリッカブルマップがズレない『RWD Image Maps』を使いこなす by 125naroom (@125naroom)
on CodePen.
HTML
<div class="imgBox"> <img src="https://125naroom.com/demo/img/sample_maru.jpg" alt="" width="1483" height="1483" usemap="#Map"> <map name="Map"> <area shape="circle" coords="375,331,154" href="#s_01"> <area shape="circle" coords="1108,331,154" href="#s_01"> <area shape="circle" coords="1108,1011,154" href="#s_01"> <area shape="circle" coords="375,1011,154" href="#s_01"> </map> </div>
CSS
.imgBox { text-align: center; margin: 50px 0; } .imgBox img { max-width: 100%; height: auto; vertical-align: top; }
jQuery
$(function(){ $('img[usemap]').rwdImageMaps(); });
『RWD Image Maps』のダウンロード
まずは『RWD Image Maps』に必要なファイルを下記サイトからダウンロードします。
jQuery RWD Image Maps on GitHub
『RWD Image Maps』の使い方
ダウンロードファイルの中で必要なファイルは以下の1点です。
- jquery.rwdImageMaps.min.js
※『min』のついてないファイルでもオッケーです。『min』が付いているファイルは改行などがない容量軽減版になります。
HTML
<script type="text/javascript" src="js/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="js/jquery.rwdImageMaps.min.js"></script>
CDNを使う場合は、
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-rwdImageMaps/1.6/jquery.rwdImageMaps.min.js"></script>
jQuery
意味は、img[usemap]は、RWD Image Mapsを適用する。
クリッカブルマップは、全て適用されるので下記を書くだけで問題なしです。
$(function(){ $('img[usemap]').rwdImageMaps(); });
hoverはjsのfocusが使える
ホバー設定がしたい時は、下記を追加します。
ただし、ブラウザによっては効かない(同じ効果にならない)のが玉に瑕です。
$(function(){ $('area').hover( function() { $(this).focus().css('outline','10px solid #000'); }, function() { $(this).blur().css('outline','none'); } ) });
イメージマップを作成してくれる便利なサイトさん
画像をドラッグするだけでとっても簡単にコードが手に入ります。
メモ
jQueryのことで何かわからないことがあればjQueryの日本語リファレンスサイトがあるので一度チェックしてみるといろいろ解決できたりしますよ。