【问题标题】:jQuery: dynamic image markers based on coordinates from data filejQuery:基于数据文件坐标的动态图像标记
【发布时间】:2016-05-26 19:54:50
【问题描述】:

我有一个图像地图和一个包含坐标列表的文件:

var coord_data = {
  "100 100": "2010-_MG_0419.jpg"
  "110 110": "2010-_MG_0412.jpg"};

我想在图像地图上的每个坐标上放置一个标记。

从@RDeving 获得一些灵感,我有一个版本可以以某种方式运行:

Fiddle Link

但如果我改变:

                $('<span class="marker"/>').css({
                "top": 100,
                "left": 200
            }).appendTo(target);

收件人:

                $('<span class="marker"/>').css({
                "top": coords[0],
                "left": coords[1]
            }).appendTo(target);

css 不适用于标记的位置。

我找了好久都白费了。

任何想法为什么它会这样?

【问题讨论】:

    标签: javascript jquery coordinates imagemap


    【解决方案1】:

    如果您在“img”DOM 元素中有图像,您可以...

    // Have some css
    img#myimage {
      position: relative;
    }
    label.icon {
      position: absolute;
    }
    
    
    //Append them dynamically
    const $imgTag = $("img#myimage");
    
    coord_data.forEach( data => {
      const coords = data.split(" ");
      $imgTag.append( $("<label>").addClass("icon").css({
        'top': coords[0],
        'left': coords[1]
      }) );
    });
    

    【讨论】:

    • 感谢您的评论。我对 jQuery 有点陌生,但我的浏览器说“coord_data.forEach”不是一个函数......
    • 也许你应该使用 for ... 循环来达到相同的结果
    • 我的代码没有错误,但对逻辑还是有点困惑。我需要在html中添加一些东西吗?否则如何将svg图标链接到网页中?
    • 我写的片段只是在数组中的每个条目的 img 元素上附加一个新标签,并在所述 x,y 坐标中分配它们,这只是一个代码伪代码示例。
    【解决方案2】:

    好的,我找到了解决方案。 如果值是“字符串”类型,我还需要添加“px”。 但如果值是“整数”类型,则不需要“px”。

    这样就可以了:

    $('<span class="marker"/>').css({
        "top": coords[0]+"px",
        "left": coords[1]+"px"
        }).appendTo(target);
    

    或者

    "top": parseInt(coords[0]),
    

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2013-09-26
      相关资源
      最近更新 更多