试图阻止点击 SVG

问题描述

各位下午好,

我是编程游戏的新手,并且已经学习过 Grasshoppers 教程。

在沙盒环境中,我正在尝试使用 JavaScript 中的 SVG 编写一个简单的“坚持下去”游戏。

我有一个背景 SVG 和一个球 SVG。

我已经给出了这两个 .on(“click”,...) 参数。

背景 SVG 将球重置为随机 cX 位置,以及 35 的 cY 位置。

球 SVG,应将球以随机 cX 转换回 cY 35,以随机 cX 转换回 1000 的 cY。

当球被点击时,它会点击背景并中断动画并立即将其返回到 cY 35 和随机 cX。

如何防止点击?

我尝试了各种随机的测试,但都没有成功。

非常感谢, TheShadows645

按要求编辑; PositionX 只是一个数组,其中包含各种数字来给出 cX。

var ball = svg.append(‘circle’).attr(‘fill’,’white’).attr(‘r’,25).attr(‘cY’,’35).attr(‘cX’,PickRandom(PosistionX));

var background =svg.append(‘rect’).attr(‘fill’,’green’).attr(‘height’,’1000’).attr(‘width’,’1000’).attr(‘cY’,’0’).attr(‘cX’,’0’);

function kickBall () {
ball.on(‘click’,() => {
    ball.transistion().attr(‘cY’,’35’).attr(‘cX’,’PickRandom(PosistionX)).duration(3000);

ball.transistion().attr(‘cY’,’1000’).attr(‘cX’,’PickRandom(PosistionX)).duration(3000);
});

编辑 2;

增加了球的大小,并减慢了动画速度。我发现球现在显然没有重置,但在第一次转换时没有上升。而是直接使用新的 PositionX。

编辑3;澄清一下,现在看来问题不是点击问题,只是原始圆形 SVG 上非常糟糕的“命中框”。但是,如果有人有任何建议,新的 .transition 问题仍然是一个问题。

解决方法

你需要做Event Delegation。在您的两个 SVG 的父级上设置一个事件,然后使用 e.target 检查事件是从哪个元素发生的,并相应地编写您的逻辑。

是这样的:(只讲逻辑)

HTML:

<div class="wrapper">
  <div class="svg1" id="svg1">SVG1</div>
  <div class="svg2" id="svg2">SVG2</div>
</div>

Javascript:

document.querySelector(".wrapper").addEventListener("click",(e)=>{
   if(event.target.id==="svg1"){
      // SVG1 logic here
   }

   if(event.target.id==="svg2"){
      // SVG2 logic here
   }
});

注意: 所以这个想法是,一旦在包装内发生点击,无论是来自 svg1 还是 svg2,我们首先交叉检查事件是哪个元素被解雇了。对于该元素,根据我们的要求设置我们的代码。 e.target.id 帮助我们了解事件从哪个元素冒泡。

,

let background = document.getElementById('background');
let ball = document.getElementById('ball');

document.addEventListener('click',(e) => {
  if (e.target.closest('#background')) {
    ball.style.top = '0px';
    ball.style.left = '0px';
  } else if (e.target.closest('#ball')) {
    ball.style.top = (Math.random() * 100) + 'px';
    ball.style.left = (Math.random() * 100) + 'px';
  }
});
svg {
  position: absolute;
}
<svg id="background" width="1000" height="1000">
  <rect width="1000" height="1000" style="fill:rgb(0,255);stroke-width:3;stroke:rgb(0,0)" />
</svg>

<svg id="ball" height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>