开发者

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.o开发者_StackOverflowffsetHeight) + "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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜