使用jQuery更改图像映射坐标值

我有一个非常复杂的图像地图,我想缩小一半.要做到这一点,需要将所有coord值除以2.由于有数千个coord值,我认为我可以使用jQuery遍历DOM来查找coord值,并将它们除以2.在 JavaScript和jQuery方面,我非常业余,而且我编写了以下代码,这些代码无法完成我的任务:

$(function(){
    $('area').each(function(){
        coord_vals= $('area'[coords]).split(',');
        new_vals= coord_vals/2;
        $('area'[coords]).val(new_vals + ',');
    });
});

这是我试图遍历的前几行HTML:

<div id="map">
    <img class="map" src="images/us_map.jpg" width="960" height="593" usemap="#usa">
    <map name="usa">
    <area href="#" title="SC" shape="poly" coords="735,418,734,419,731,416,729,413,727,411,725,410,723,405,720,399,716,398,714,396,713,393,711,391,709,390,707,387,704,385,699,383,382,697,379,696,378,693,373,690,686,371,684,369,368,685,366,687,365,363,360,701,356,708,355,724,728,732,359,745,358,747,760,769,374,764,762,761,759,392,758,394,756,395,754,751,401,749,404,748,744,408,741,409,742,412,737,417,735,418"></area>
    <area href="#" title="HI" shape="poly" coords="225,521,227,518,229,517,225,521"></area>
    <area href="#" title="HI" shape="poly" coords="235,241,520,243,244,516,513,240,512,236,514,235,518"></area>

解决方法

你可以这样做:

$("area").each(function() {
    var pairs = $(this).attr("coords").split(',');
    for(var i=0; i<pairs.length; i++) {
        var nums = pairs[i].split(',');
        for(var j=0; j<nums.length; j++) {
            nums[j] = parseFloat(nums[j]) /2;
        }
        pairs[i] = nums.join(',');
    }
    $(this).attr("coords",pairs.join(','));
});

这样可以保持格式并仔细转换每个格式,这是输出

<div id="map">
  <img class="map" src="images/us_map.jpg" width="960" height="593" usemap="#usa"> 
  <map name="usa"> 
    <area href="#" title="SC" shape="poly" coords="367.5,209,367,209.5,365.5,208,364.5,206.5,363.5,205.5,362.5,205,361.5,202.5,199.5,199,357,198,356.5,196.5,355.5,195.5,354.5,195,353.5,193.5,352,192.5,349.5,191.5,191,348.5,189.5,348,189,346.5,186.5,345,343,185.5,342,184.5,184,342.5,183,343.5,182.5,181.5,180,350.5,178,354,177.5,362,364,179.5,372.5,179,373.5,380,384.5,187,381,380.5,379.5,196,197,197.5,377,375.5,200.5,374.5,202,372,204,370.5,204.5,206,368.5,208.5,367.5,209">
    <area href="#" title="HI" shape="poly" coords="112.5,260.5,113.5,259,114.5,258.5,112.5,260.5">
    <area href="#" title="HI" shape="poly" coords="117.5,120.5,260,121.5,122,258,256.5,120,256,118,257,117.5,259"> 
  </map>
</div>

You can give it a try here.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...