添加超时时,JavaScript代码停止工作
我正在尝试将一个名为按下的类添加到一个名为 w 类的元素中。当用户单击包含类 w 的元素时,这将发生。然后,我想在延迟100延迟后删除class 按。这是我写的代码。
(
简
- 而评论此部分
settimeout(foo(this.InnerText),100);
甚至document.queryselector(“。”+this.innertext).classlist.add(“ perted”); <<< /代码>未被执行。
document.querySelector('.w').addEventListener("click",function () {
document.querySelector("."+this.innerText).classList.add("pressed");
// setTimeout(foo(this.innerText), 100);
});
function foo(stringclass) {
document.querySelector("."+stringclass).classList.remove("pressed");
console.log(stringclass);
}
有人可以帮我吗?
HTML代码
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Drum Kit</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
</head>
<body>
<h1 id="title">Drum
I am trying to add a class named pressed to an element with class named w. This will happen when user clicks on element containing class w. I then want to remove the class press after delay of 100.So this is the code I have writtten.
(In short: I am trying to add animation with js by adding(and then removing after 100ms) a CSS class pressed.)
But this is not working, it's behavior is as follows:
- When I un-comment this part
setTimeout(foo(this.innerText), 100);
even thedocument.querySelector("."+this.innerText).classList.add("pressed");
isn't getting executed.
document.querySelector('.w').addEventListener("click",function () {
document.querySelector("."+this.innerText).classList.add("pressed");
// setTimeout(foo(this.innerText), 100);
});
function foo(stringclass) {
document.querySelector("."+stringclass).classList.remove("pressed");
console.log(stringclass);
}
Can anyone help me with this please?
HTML Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Drum Kit</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Arvo" rel="stylesheet">
</head>
<body>
<h1 id="title">Drum ???? Kit</h1>
<div class="set">
<button class="w drum">w</button>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
CSS Class
.pressed {
box-shadow: 0 15px 40px 0 #DBEDF3;
opacity: 0.5;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
settimeout(foo(this.innertext),100);
立即执行foo
。您需要传递功能本身。我相信您想要更接近的东西
document.queryselector('。w')。addeventListener(“ click”,function(e){document.queryselector(“。”+e.target.innertext).classlist.add(“ perseDed”) function(){foo(e.target.innertext)},100);});
setTimeout(foo(this.innerText), 100);
executesfoo
immediately. You need to pass the function itself.I believe you want something closer to
document.querySelector('.w').addEventListener("click",function (e) { document.querySelector("."+e.target.innerText).classList.add("pressed"); setTimeout(function() {foo(e.target.innerText)}, 100); });