통합검색

Javascript

[jQuery] 이미지맵 반응형 적용하기 (area 태그)



반응형 사이트의 경우 PC기준으로 이미지맵(area) 태그 작성 후
모바일에서 이미지 사이즈가 축소되었을 때 축소된 비율 만큼 area 좌표를 자동 조정해주는 코드.


[!]jQuery[/!] 
$(document).ready(function(){

    //이미지맵이 있는 경우 반응형 이미지맵 처리
    var coords = new Array();
    function imagemap_coords(type = ''){
        $('area[response_croods]').each(function(idx){
            if(type=='ready'){
                coords[idx] = $(this).attr('coords');
            }
            var map_id = $(this).parent('map').attr('name');
            var $img = $('img[usemap="#'+map_id+'"]');
            var org_width = parseInt($img[0].naturalWidth);
            var now_width = $img.width();
            var croods_exp = coords[idx].split(',');
            var coords_re = '';
            for(var i=0;i<croods_exp.length;i++){
                coords_re += ','+croods_exp[i]*(now_width/org_width);
            }
            coords_re = coords_re.substring(1);
            $(this).attr('coords',coords_re);
        });
    }
    imagemap_coords('ready');
    $(window).resize(imagemap_coords);
});

[!]HTML[/!] 
<area shape="rect" alt="" title="" coords="472,24,507,64" href="" target="" response_coords />