简体   繁体   English

jQuery addEventListener by querySelector不起作用

[英]javascript addEventListener by querySelector not work

HI this is my javascript code : 这是我的javascript代码:

window.onload = function () {

    function hideAds() {
        setTimeout(hide, 2000);
    }

    function hide() {
        var ads = document.querySelector(".ads");
        ads.style.marginTop = (-ads.offsetHeight) + "px";
    }

    function reveal() {
        ads.style.marginTop = "";
        hideAds();
    }
    var ads = document.querySelector(".ads");
    ads.addEventListener("click", reveal, true);


    hideAds();

}

from this code, everything work fine other then "ads.addEventListener" second line from last. 从这个代码,一切正常,然后“ads.addEventListener”第二行从最后。 what is the reason? 是什么原因? is i made anything wrong here..? 我在这里做错了什么..?

i need to call my reveal function by click the ads class added div. 我需要通过点击广告类添加div来调用我的显示功能。

any one help me? 任何人帮助我?

The code you gave should work as it is. 你提供的代码应该按原样运行。 jsFiddle 的jsfiddle

But I'd be tempted to re-factor your code like so. 但我很想重新考虑你的代码。

HTML HTML

<div class="ads">Blah blah blah</div>

Javascript 使用Javascript

function setMarginTop(element, marginTop) {
    element.style.marginTop = marginTop || null;
}

function hideAds(element, marginTop, ms) {
    setTimeout(function() {
        setMarginTop(element, marginTop);
    }, ms || 2000);
}

window.addEventListener('load', function () {
    var ads = document.querySelector('.ads'),
        hide = (-ads.offsetHeight) + 'px';

    hideAds(ads, hide);
    ads.addEventListener('click', function (evt) {
        var target = evt.target;

        setMarginTop(target)
        hideAds(target, hide);
    }, false);
}, false);

On jsFiddle jsFiddle上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM