制作 JavaScript 代码适用于任何元素

Making a JavaScript code works with any element

本文关键字:任何 元素 适用于 代码 JavaScript 制作      更新时间:2023-09-26
document.getElementById("but").onclick = showDropDown;
function showDropDown(e) {
    document.getElementById("but").onclick = function() {};
    if (e.stopPropagation) e.stopPropagation(); // W3C model
    else e.cancelBubble = true; // IE model
    document.getElementById("window").style.display = "inline-block";
    document.onclick = function(e) {
        var ele = document.elementFromPoint(e.clientX, e.clientY);
        if (ele == document.getElementById("but")) {
            hideDropDown();
            return;
        }
        do {
            if (ele == document.getElementById("window")) return;
        } while (ele = ele.parentNode);
        hideDropDown();
    };
}
function hideDropDown() {
    document.onclick = function() {};
    document.getElementById("window").style.display = "none";
    document.getElementById("but").onclick = showDropDown;
}​

<input id="but" type="button" value="pressMe" />
<div id="window" style="display:none">popup</div>

演示:http://jsfiddle.net/nazym/

我试图使用变量而不是指定元素的名称使 JavaScript 代码动态化,但我做不到。它总是返回错误。我想将它与不同的元素联系起来。

更新
我想用变量替换 JavaScript 代码中元素的id,以便我可以将其与任何元素一起使用。我试图这样做,但失败了。基本上,我想使用变量而不是元素的id,并以某种方式再次将其链接到元素。

改用参数:

function showDropDown(element, e) {
    element.onclick = function() {};
    // ....
    hideDropDown(element);
}

你会给元素它的onclick事件处理程序,如下所示:

document.getElementById('but').onclick = function(event) {
    showDropDown(this, event);
};

演示:http://jsfiddle.net/xNSZm/

将代码更改为

var showDropdown = function(e) { ... };
document.getElementById("but").onclick = showDropDown;

换句话说,在赋值函数之前将函数存储在变量中。

在你的代码中:

> document.onclick = function(e){

在支持 IE 事件模型的浏览器中,e将是未定义的。要适应这些浏览器,您可以使用:

    e = e || window.event;

要查找单击的元素,而不是:

>   var ele = document.elementFromPoint(e.clientX, e.clientY);

你可以做:

    var ele = e.target || e.srcElement;

它将在比elementFromPoint更多的浏览器中工作,因此应该更可靠,更快。