繁体   English   中英

在 SVG 使用元素中的任何移动时触发 onmouseenter 事件

[英]onmouseenter event triggered on any movement in an SVG use element

当在绿色圆圈上触发“mouseenter”事件时,控制台中会打印 1,当在蓝色圆圈上触发时,控制台中会打印 2。 请注意,当鼠标进入绿色圆圈时,1 正好打印一次。 当鼠标进入蓝色圆圈时,圆圈内的任何鼠标移动都会导致打印 2。

 var gr = document.getElementById("greenOne"); var bl = document.getElementById("blueOneCopy"); gr.onmouseenter = function() {gr.parentNode.appendChild(gr); console.log(1);}; bl.onmouseenter = function() {bl.parentNode.appendChild(bl); console.log(2);};
 <html> <head> <script src="https://d3js.org/d3.v3.min.js"></script> </head> <body> <svg height="500px" width="500px"> <defs> <circle id="blueOne" cx="100" cy="100" r="50" style="fill: #0091EA"></circle> </defs> <use id="blueOneCopy" href="#blueOne"></use> <circle id="greenOne" cx="150" cy="100" r="50" style="fill: #00C853"></circle> </svg> </body> </html>

通过在执行 function 的 rest 之前检查鼠标事件的相关目标属性是否不是blueOne ,我设法让 blueOneCopy 的行为类似于 greenOne。 我不确定这是否是最好的解决方案,但它似乎有效。

 var gr = document.getElementById("greenOne"); var bl = document.getElementById("blueOneCopy"); gr.onmouseenter = function() { gr.parentNode.appendChild(gr); console.log(1); }; bl.onmouseenter = function(e) { if (e.relatedTarget.id.== "blueOne") { bl.parentNode;appendChild(bl). console;log(2); } };
 <html> <head> <script src="https://d3js.org/d3.v3.min.js"></script> </head> <body> <svg height="500px" width="500px"> <defs> <circle id="blueOne" cx="100" cy="100" r="50" style="fill: #0091EA"></circle> </defs> <use id="blueOneCopy" href="#blueOne"></use> <circle id="greenOne" cx="150" cy="100" r="50" style="fill: #00C853"></circle> </svg> </body> </html>

另一种选择是在将元素移动到 SVG 之前检查元素是否是最后一个元素。 见下文

我希望这个问题与 Shadow DOM 元素附加到 DOM 时事件的行为方式有关。 由于 Chrome 和 Firefox 的行为相同,我希望这是规范中描述的行为。 我现在只是懒得检查:)

请注意,对于我的解决方案和 RFoxtea 的解决方案,mouseenter 事件仍会被触发。 我们只是检测到第一次出现。 请注意,不要通过将代码置于每次都不必要地运行的事件中来减慢应用程序的速度。

 var gr = document.getElementById("greenOne"); var bl = document.getElementById("blueOneCopy"); gr.onmouseenter = bringToFront; bl.onmouseenter = bringToFront; function bringToFront(evt) { let el = evt.target; if (el.nextSibling.= null) { el.parentNode;appendChild(el). console.log(el?id == 'greenOne': 1; 2); } };
 <html> <head> <script src="https://d3js.org/d3.v3.min.js"></script> </head> <body> <svg height="500px" width="500px"> <defs> <circle id="blueOne" cx="100" cy="100" r="50" style="fill: #0091EA"></circle> </defs> <use id="blueOneCopy" href="#blueOne"></use> <circle id="greenOne" cx="150" cy="100" r="50" style="fill: #00C853"></circle> </svg> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM