简体   繁体   中英

javascript addEventListener by querySelector not work

HI this is my javascript code :

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. what is the reason? is i made anything wrong here..?

i need to call my reveal function by click the ads class added div.

any one help me?

The code you gave should work as it is. jsFiddle

But I'd be tempted to re-factor your code like so.

HTML

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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