在mousemove和click上都改变状态

时间:2015-04-16 12:45:29

标签: javascript click mousemove

我有这个javascript,在4秒不活动后隐藏div。

var timeout;
var isHidden = false;

function hideOnIdle() {
if (timeout) {
    clearTimeout(timeout);
}
timeout = setTimeout(function() {
    if (!isHidden) {
        document.getElementById("slide").style.opacity = "0";
        isHidden = true;
    }
}, 4000);
if (isHidden) {
    document.getElementById("slide").style.opacity = "1";
    isHidden = false;
}
}

if (document.addEventListener) {
document.addEventListener("mousemove", hideOnIdle);
} else {
document.attachEvent("mousemove", hideOnIdle);
}

如果移动鼠标,这将再次显示div。

如何修改javascript并再次显示div?

https://jsfiddle.net/Lcqumf2y/

感谢。

1 个答案:

答案 0 :(得分:0)

我改变了你的JsFiddle示例:

var timeout;
var isHidden = false;

function hideOnIdle() {
    if (timeout) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(function() {
        if (!isHidden) {
            hide();
        }
    }, 4000);
    if (isHidden) {
        show();
    }
}

function hide() {
    document.getElementById("slide").style.opacity = "0";
    isHidden = true;
}

function show() {
    document.getElementById("slide").style.opacity = "1";
    isHidden = false;
}

if (document.addEventListener) {
    document.addEventListener("mousemove", hideOnIdle);
    document.addEventListener("click", hideonIdle);
} else {
    document.attachEvent("mousemove", hideOnIdle);
}
#slide {
    transition: all .2s linear;
}
<div id="slide">ABC123</div>