javascript - 如何将 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";
}
错误是:当我单击元素时,没有反应。虽然它正常改变位置。
有什么建议吗?
解决方案
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");
};
推荐阅读
- c# - 在 wpf 中关闭窗口之前强制发送 MQTT 消息?
- sql - 查找每组丢失物品的数量(ORACLE SQL)
- sql-server - 找不到指定的文件 | SSIS | 在 SQL Server 上使用 Dtexec 执行包 SSIS
- apache-kafka - 如何用kafka和spring处理老消费者话题中的新事件
- netlogo - 随机发新补丁?
- javascript - 在自定义挂钩中同步状态
- automation - 我如何断言结果只有我搜索的内容?
- python - 如何将模块名称转换为相对路径?
- python - Python popen 在 stderr 中给了我一个空字节字符串
- swift - 如何在我的线程中修复“致命错误:索引超出范围”