javascript - 如何单击具有更多边界的 svg 线标记?

标签 javascript html web svg frontend

我每天都感谢开发者的回复。 如何单击具有更多边界的 svg 线标记?

这是我的线路标签。 enter image description here

这是我想要点击ling标签的边界。 enter image description here

  <body>
    <svg height="210" width="500">
      <defs>
        <filter id="f1" x="0" y="0" width="200%" height="200%">
          <feOffset result="offOut" in="SourceGraphic" dx="2" dy="2" />
          <feBlend in="SourceGraphic" in2="offOut" mode="normal" />
        </filter>
      </defs>
      <line
        x1="0"
        y1="0"
        x2="200"
        y2="200"
        style="stroke:rgb(255,0,0);stroke-width:5;box-shadow: 10px 5px 5px red;"
      ></line>
    </svg>
  </body>
  <script>
    document
      .getElementsByTagName("line")[0]
      .addEventListener("click", function(e) {
        console.log("lineClick", e);
      });
  </script>

如何设置更多的点击事件边界?

最佳答案

在第一条线的顶部添加第二条更宽的不可见线,捕获其点击并将其分派(dispatch)到下面的可见线。

  <body>
    <svg height="210" width="500">
      <defs>
        <filter id="f1" x="0" y="0" width="200%" height="200%">
          <feOffset result="offOut" in="SourceGraphic" dx="2" dy="2" />
          <feBlend in="SourceGraphic" in2="offOut" mode="normal" />
        </filter>
      </defs>
      <line
        x1="0"
        y1="0"
        x2="200"
        y2="200"
        style="stroke:rgb(255,0,0);stroke-width:5;box-shadow: 10px 5px 5px red;"
      ></line>
      <line onclick="document
      .getElementsByTagName('line')[0].dispatchEvent(new Event('click'));"
        x1="0"
        y1="0"
        x2="200"
        y2="200"
        style="stroke:none;stroke-width:40;pointer-events:all;cursor:pointer"
      ></line>
      </svg>
  </body>
  <script>
    document
      .getElementsByTagName("line")[0]
      .addEventListener("click", function(e) {
        console.log("lineClick", e);
      });
  </script>

关于javascript - 如何单击具有更多边界的 svg 线标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824706/

相关文章:

javascript - 如何在 dotnetbrowser 中获得文本区域的焦点?

javascript - 无法将表单标签添加到表中

javascript - jQuery 选择器多选菜单/正则表达式

Javascript 使用图像将视频静音/取消静音

javascript - 如何使用类和函数为 html5-canvas 上的多个对象设置动画?

javascript - 使用 setTimeout 在 Canvas 中设置动画时出现问题

html - 使用 html 文件中的链接创建搜索框?

javascript - 由于文档准备好且 DOM 较大,jquery 点击触发速度非常慢

javascript - 向下滚动时滚动绑定(bind)隐藏标题,反之亦然

php - 传递具有特殊字符的字符串