live addEventListener mouseenter

时间:2014-01-25 15:00:02

标签: javascript jquery google-chrome addeventlistener

我有jQuery的代码:

$(document).on("mouseenter","a",function(e){
    //...
});

如何使用本机JavaScript(不使用jQuery)创建相同的内容?

我只需要与Chrome兼容。

2 个答案:

答案 0 :(得分:4)

对于相同的功能,您可以在其中向单个元素添加多个事件侦听器,请使用以下命令:

addEventListener('mouseover', function(e) {
    if (e.target instanceof HTMLAnchorElement) {
        //...
    }
});

那将完全相同。对于其他选择者:

addEventListener('mouseover', function(e) {
    if (e.target instanceof HTMLAnchorElement) {
        //matches if the element is an <a>
    }
    if (e.target.className.match(/(\s|^)foobar(\s|$)/)) {
        //matches if the element has the class "foobar" in its classes list
    }
    if (e.target.id == 'baz') {
        //matches if the element has an id of "baz"
        //same syntax works for attributes like 'name', 'href', 'title', etc.
    }
    if (e.target instanceof HTMLLabelElement && e.target.attributes.for.value == 'baz') {
        //matches a <label> tag that has its 'for' attribute set to 'baz'
        //the element.attributes.attrName.value is the syntax for getting the value
        //    of any attribute that isn't available otherwise
    }
});

委派mouseenter事件的问题在于它只会在应用它的元素悬停时触发。换句话说,如果将mouseenter事件附加到文档中,就像在jQuery代码中一样,它只会在使用鼠标输入document时触发,而不会在任何子项中输入。为了使其适用于儿童,您需要使用mouseover

答案 1 :(得分:0)

这可以优化新旧浏览器的兼容性。

Live Demo

var links = document.links || document.anchors || document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    addEvent(links[i], 'mouseenter', action);
}

function addEvent(element, myEvent, fnc) {
    return ((element.attachEvent) ? element.attachEvent('on' + myEvent, fnc) : element.addEventListener(myEvent, fnc, false));
}

function action(evt) {
    var e = evt || window.event,
        link = (e.currentTarget) ? e.currentTarget : e.srcElement;
    link.style.color = "lime";
}