在没有jquery的情况下处理元素外部的点击 [英] Handling clicks outside an element without jquery

查看:64
本文介绍了在没有jquery的情况下处理元素外部的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实施这样的解决方案

I would like to implement the solution like this

如何检测元素外部的点击?

但是我使用的是已经定义了$()函数的另一个JavaScript库

but I'm using another javascript library with $() function already defined

有什么建议吗?

推荐答案

这很容易实现.仅为一项功能加载jQuery库会很可惜.

This is easy to accomplish. Would be a shame to load the jQuery library just for one feature.

如果您正在使用的其他库处理事件绑定,则可以在该库中执行相同的操作.由于您没有指出其他库是什么,因此有一个本机解决方案:

If the other library you're using handles event binding, you could do the same thing in that library. Since you didn't indicate what that other library is, here's a native solution:

示例: http://jsfiddle.net/patrick_dw/wWkJR/1/

window.onload = function() {

    // For clicks inside the element
    document.getElementById('myElement').onclick = function(e) {
            // Make sure the event doesn't bubble from your element
        if (e) { e.stopPropagation(); } 
        else { window.event.cancelBubble = true; }
            // Place the code for this element here
        alert('this was a click inside');
    };

    // For clicks elsewhere on the page
    document.onclick = function() {
        alert('this was a click outside');
    };
};

这篇关于在没有jquery的情况下处理元素外部的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆