要使用 Konva 移除事件监听器,我们可以使用形状对象的 off()
方法,该方法需要一个事件类型,例如点击或鼠标按下。
说明:点击圆形以查看从 onclick 事件绑定触发的警报。通过点击按钮移除事件监听器,然后再次点击圆形以观察事件绑定已被移除。
Konva Remove_Event Demoview raw<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script> <meta charset="utf-8" /> <title>Konva Remove Event Listener Demo</title> <style> body { margin: 0; padding: 0; overflow: hidden; background-color: #f0f0f0; }
#buttons { position: absolute; top: 5px; left: 10px; } </style> </head>
<body> <div id="container"></div> <div id="buttons"> <button id="removeClick">Remove onclick</button> </div> <script> function writeMessage(message) { text.text(message); }
var stage = new Konva.Stage({ container: 'container', width: window.innerWidth, height: window.innerHeight, });
var layer = new Konva.Layer();
var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2 + 10, radius: 70, fill: 'red', stroke: 'black', strokeWidth: 4, });
circle.on('click', function () { alert('You clicked on the circle'); });
layer.add(circle); stage.add(layer);
document.getElementById('removeClick').addEventListener( 'click', function () { circle.off('click'); alert('onclick removed'); }, false ); </script> </body> </html>
|