首页 > 解决方案 > 如何将 onclick 嵌入到另一个函数中

问题描述

我想实现这个逻辑:当鼠标在一个带有 id 的元素上移动时"spirit",休眠一段时间然后改变元素的位置。但是,如果用户单击 中的元素,则会"sleep period"发出一条消息。

所以这就是我的代码:

    function changePos() {


        let img = document.getElementById("spirit");


        // "sleep"
        let now = new Date().getTime();
        while ( new Date().getTime() < now + 1000 ){

            if (img.onclick == true){
                alert("Click Success")
            }

        }

        // change position
        img.style.left = Math.random()*innerWidth+"px";
        img.style.top = Math.random()*innerHeight+"px";

    }

错误是:当我单击元素时,没有反应。虽然它正常改变位置。

有什么建议吗?

标签: javascript

解决方案


var timeOutVariable = null;
var timeOutDuration = yourtimeoutduration;
document.getElementById("spirit").onmouseover = function(){
     if (timeOutVariable !== null) {
         clearTimeout(timeOutVariable );
     }
     timeOutVariable = setTimeout(function(){
         document.getElementById("spirit").style.left = Math.random()*innerWidth+"px";
         document.getElementById("spirit").style.top = Math.random()*innerHeight+"px";
     }, timeOutDuration);
}

document.getElementById("spirit").onclick = function(){
    if (timeOutVariable !== null) {
         clearTimeout(timeOutVariable );
         timeOutVariable = null;
     }
    alert("Click success");
};

推荐阅读