首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >html画布陷阱左键单击并允许右击通过(指针事件)

问html画布陷阱左键单击并允许右击通过(指针事件)
EN

Stack Overflow用户
提问于 2013-12-26 16:12:48
回答 1查看 1.3K关注 0票数 0

用例是,我在几个html元素之上有一个html画布,用于监听鼠标右键单击事件。我想使用鼠标左键在画布上绘制,同时使用鼠标右键与底层html元素交互。

我知道我可以通过设置css属性pointer-events为none来允许所有鼠标事件通过画布。然而,我想只允许右击通过它。

实现这一点的一种方法可能是在画布上监听右键单击,在回调中将pointer-events设置为none,再次手动激发右键单击事件,并将pointer-events设置回自动。

顺便说一句,我使用的是KineticsJS,我不知道如何使用它手动触发鼠标事件。

如有任何建议,我们将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2013-12-28 00:30:23

有趣的话题引起了我的注意。提出一个基于this jQuery approach和其他一些解决方案是很有趣的。我不熟悉KineticsJS,但这是一种简单的javascript方法

从本质上讲,您可以通过使用对象的尺寸/位置和onmousedown的pointer-events:none来确定是否在背景元素上单击了右键,从而为右键单击伪造一个event.which。

代码语言:javascript
复制
// 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";
        }
    }
}

​

​

我希望它能满足你的需要!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20781464

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档