javascript - 我该如何为此编写javascript和html代码?
问题描述
我想制作一个包含字母的网格(如上图所示)并有一个像闪烁这样的过渡事件。它在连续循环中持续闪烁一段时间(例如第一个 a 之后 b .. 等等),当我按 Enter 时,它应该输出闪烁使用 javascript 和 HTML 的字母我已经尝试过代码以下。
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
<style>
.keys {
display: flex;
}
.key {
border: .4rem solid black;
border-radius: .5rem;
margin: 1rem;
font-size: 1.5rem;
padding: 1rem .5rem;
width: 5rem;
text-align: center;
background: rgba(0, 0, 0, 0.4);
transition: all 0.07s ease;
}
.playing {
transform: scale(1, 1);
border-color: #ffc600;
box-shadow: 0 0 1rem #ffc600;
}
</style>
</head>
<body>
<div class="keys">
<div class="key">A</div>
<div class='key'>B</div>
<div class='key'>C</div>
<div class='key'>D</div>
<div class='key'>E</div>
<div class='key'>F</div>
</div>
<script>
key.ClassList.add('playing');
</script>
</body>
</html>
解决方案
你可以这样做 -
let curr_div_on = 0,
curr_div_off = 0;
// get the div on whose child we want to apply this effect
const key = document.getElementsByClassName("key");
// this function will toggle on the effect
function setPlayingOn() {
key[curr_div_on % 6].classList.add("playing");
curr_div_on = (curr_div_on + 1) % 6; // taking modulo to ensure index remains within bound and effect start from first once it reaches end
}
// this function will toggle off the effect
function setPlayingOff() {
key[curr_div_off % 6].classList.remove("playing");
curr_div_off = (curr_div_off + 1) % 6;
}
// setInterval will set to call the toggle on function every 500ms
setInterval(setPlayingOn, 500);
// setInterval will set to call the toggle on function every 500ms. But here setTimeout is used to delay the first call made to toggle_playing_off
setTimeout(() => setInterval(setPlayingOff, 500), 500);
document.addEventListener("keypress", function() {
console.log(curr_div_on);
});
/* use display as flex and a fixed wdith so last 3 divs wrap off and go below as you wanted*/
#keys {
display: flex;
justify-content: center;
width: 30rem;
flex-wrap: wrap;
}
.key {
border: 0.4rem solid black;
border-radius: 0.5rem;
margin: 1rem;
font-size: 1.5rem;
padding: 1rem 0.5rem;
width: 5rem;
text-align: center;
background: rgba(0, 0, 0, 0.4);
transition: all 0.07s ease;
}
.playing {
transform: scale(1, 1);
border-color: #ffc600;
box-shadow: 0 0 1rem #ffc600;
}
<div id="keys">
<div class="key">A</div>
<div class='key'>B</div>
<div class='key'>C</div>
<div class='key'>D</div>
<div class='key'>E</div>
<div class='key'>F</div>
</div>
如果您不了解我在答案中提到的内容并且没有通过我的评论解释得到正确的理解,您可以在这里了解更多关于它们的信息 -
推荐阅读
- r - 根据另一列的条件获取值
- java - Java Stream vs Flux fromIterable
- java - 使用键时未获取从映射返回的特定数组
- ssl - 将 .pem 证书组合到 truststore/keystore.jsk
- excel - 分配给范围时出错:参数数量错误
- python - 用于过滤熊猫数据框列中的值的自定义函数
- javascript - 如何根据使用选择框选择的值从数据库中检索特定记录?
- c++ - 从程序中获取 cmake 选项
- python - Slim Python Dockerfile 未执行
- c# - asp .net 核心中 IHostedService.StartAsync 中的 CancellationToken 有什么意义?