用例是,我在几个html元素之上有一个html画布,用于监听鼠标右键单击事件。我想使用鼠标左键在画布上绘制,同时使用鼠标右键与底层html元素交互。
我知道我可以通过设置css属性pointer-events为none来允许所有鼠标事件通过画布。然而,我想只允许右击通过它。
实现这一点的一种方法可能是在画布上监听右键单击,在回调中将pointer-events设置为none,再次手动激发右键单击事件,并将pointer-events设置回自动。
顺便说一句,我使用的是KineticsJS,我不知道如何使用它手动触发鼠标事件。
如有任何建议,我们将不胜感激。
发布于 2013-12-28 00:30:23
有趣的话题引起了我的注意。提出一个基于this jQuery approach和其他一些解决方案是很有趣的。我不熟悉KineticsJS,但这是一种简单的javascript方法
从本质上讲,您可以通过使用对象的尺寸/位置和onmousedown的pointer-events:none来确定是否在背景元素上单击了右键,从而为右键单击伪造一个event.which。
// Get all overlaying canvases
var canvas = document.getElementsByTagName("canvas"),
// Get all elements that you want the click to fire on
background = document.getElementsByClassName("background");
// Use click location and dimensions/positioning to fake a click through
function passThrough(e) {
// Allow only right click to pass through
if(e.which == 2 || e.which == 3) {
// Check all background elements
for(var i = 0; i < background.length; i++) {
// check if clicked point (taken from event) is inside element
var mouseX = e.pageX;
var mouseY = e.pageY;
var obj = background[i];
var width = obj.clientWidth;
var height = obj.clientHeight;
if (mouseX > obj.offsetLeft && mouseX < obj.offsetLeft + width
&& mouseY > obj.offsetTop && mouseY < obj.offsetTop + height) {
// Force click event if within dimensions
background[i].onclick();
}
}
}
}
for(var i = 0; i < canvas.length; i++) {
// Force our function when clicked
canvas[i].onmousedown = passThrough;
// Prevent menu from appearing
canvas[i].oncontextmenu = function(event) { event.returnDefault; return false; }
}
for(var i = 0; i < background.length; i++) {
// Toggle background when clicked (to show it works)
background[i].onclick = function() {
if(this.style.background == "black") {
this.style.background = "red";
}
else {
this.style.background = "black";
}
}
}

我希望它能满足你的需要!
https://stackoverflow.com/questions/20781464
复制相似问题