HTML热区map坐标,随窗口大小自适应办法(javascript)

为图片添加MAP:

<img src='https://www.qulaba.com/logo.png' width='100%' heigh='100%' usemap='#planetmap'/>  
<map id="planetmap" name="planetmap">  
   <area shape="rect" id="41" coords="143,789,494,836" href="https://www.taiyoubang.com" title="太友帮"  
/>  
   <area shape="rect" id="42" coords="202,1556,460,1693" href="https://www.lajiaoyun.cn" title="辣椒云"  
/>  
   <area shape="rect" id="43" coords="202,2036,460,2082" href="http://www.abyouhuiquan.com" title="爱帮优惠券"  
 />
</map>

图片大小随页面变化,需要map中每个area的坐标也随页面等比例变化。
JavaScript实现:

<script type="text/javascript">  
  
        adjust();  
  
        var timeout = null;//onresize触发次数过多,设置定时器  
        window.onresize = function () {  
            clearTimeout(timeout);  
            timeout = setTimeout(function () { window.location.reload(); }, 100);//页面大小变化,重新加载页面以刷新MAP  
        }  
  
        //获取MAP中元素属性  
        function adjust() {  
            var map = document.getElementById("CribMap");  
            var element = map.childNodes;  
            var itemNumber = element.length / 2;  
            for (var i = 0; i < itemNumber - 1; i++) {  
                var item = 2 * i + 1;  
                var oldCoords = element[item].coords;  
                var newcoords = adjustPosition(oldCoords);  
                element[item].setAttribute("coords", newcoords);  
            } 
        }  
  
        //调整MAP中坐标  
        function adjustPosition(position) {  
            var pageWidth = document.body.clientWidth;//获取页面宽度  
            var pageHeith = document.body.clientHeight;//获取页面高度  
  
            var imageWidth = 1160;<span style="white-space:pre">    </span>//图片的长宽  
            var imageHeigth = 990;  
  
            var each = position.split(",");  
            //获取每个坐标点  
            for (var i = 0; i < each.length; i++) {  
                each[i] = Math.round(parseInt(each[i]) * pageWidth / imageWidth).toString();//x坐标  
                i++;  
                each[i] = Math.round(parseInt(each[i]) * pageHeith / imageHeigth).toString();//y坐标  
            }  
            //生成新的坐标点  
            var newPosition = "";  
            for (var i = 0; i < each.length; i++) {  
                newPosition += each[i];  
                if (i < each.length - 1) {  
                    newPosition += ",";  
                }  
            }  
            return newPosition;  
        }  
</script>  

相关推荐