【问题标题】:Why do areas in Chrome not have a width?为什么 Chrome 中的区域没有宽度?
【发布时间】:2016-09-14 04:10:41
【问题描述】:

我有一个特殊的用例,我需要获取 的宽度和高度,以及它的偏移量。

在 IE11 上,它按预期工作,即我可以做到

$("area:eq(1)").offset().left;
$("area:eq(1)").outerWidth();

但在 Chrome 中,offset 似乎返回 MAP 父级的左上角坐标,而 width 和 height 返回 0。

在我完全改变我的方法并分解一堆代码之前,有没有办法让 Chrome 在这方面表现得像 IE? (有趣,这不是我想问的问题,哈哈 :))

<img name="index" src="index.jpg" width="3500" height="973" border="0" id="index" usemap="#m_index" alt="">
  <map name="m_index" id="m_index">
    <area shape="rect" coords="173,95,249,237" href="javascript:;" alt="">
    <area shape="rect" coords="94,95,170,237" href="javascript:;" alt="">
    <area shape="rect" coords="12,94,88,236" href="javascript:;" alt="">
  </map>

【问题讨论】:

    标签: jquery html image google-chrome imagemap


    【解决方案1】:

    我发现最近提交的 Chrome 错误报告,似乎与您的问题有关:https://bugs.chromium.org/p/chromium/issues/detail?id=606506

    报告中提到,该区域的默认样式display: inline; width: 0; height: 0 导致了该问题。 基于此,我尝试了一种样式解决方法,将display:block; 添加到样式中。 这导致在 Chrome 中返回错误的宽度和零高度

    <area shape="rect" coords="94,95,170,237" style="display:block;" href="javascript:;" alt="">
    
    $("area:eq(1)").outerWidth(); //returns 280 instead of 76
    $("area:eq(1)").outerHeight(); //returns 0 instead of 142
    

    通过将widthheight 添加到样式中,它可以工作,但是为每个区域添加特定样式可能是繁琐的工作。

    似乎没有一个合理的“修复”可以让 Chrome 的行为像 IE,除了等到 bug 解决。

    最好的解决方法同时我能想到的,是使用coords属性计算宽度和高度:

    var area = $("area[shape=rect]").eq(1); //select areas with rectangle shape only
    var coords = area.attr('coords').split(','); 
    
    var x1 = coords[0],
    y1 = coords[1],
    x2 = coords[2],
    y2 = coords[3];
    
    var width = Math.abs(x1-x2);
    var height = Math.abs(y1-y2);
    

    您也可以使用坐标来计算偏移量,并为其他形状创建类似的解决方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      相关资源
      最近更新 更多