gpt4 book ai didi

javascript - jQuery - 改变颜色

转载 作者:搜寻专家 更新时间:2023-10-31 08:13:05 26 4
gpt4 key购买 nike

刚开始学习一些 jQuery。我一直在看一些关于 w3schools 的教程。我的目标是在按下按键时更改形状颜色。我可以为按钮执行此操作,但不能为形状执行此操作。

我正在使用退格键代码 8,我正在使用这个

$("button").keydown(function(e) {
if(e.which === 8) {
$(this).css("background-color", "black");
}
});
$("button").keyup(function() {
$(this).css("background-color", "yellow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button>
Color
</button>

例如,我将如何执行以下操作。我尝试了几种方法,但似乎无法正常工作。为什么将选择器更改为类名不起作用?任何提示都不胜感激。谢谢

.shape{
width: 40px;
height: 40px;
background-color: pink;
}
<div class="shape">

最佳答案

您的 button 本身接受键盘焦点,而您的 div 不接受。将此添加到 .shape:

<div class="shape" tabindex="0"></div>

演示

$(".shape").keydown(function(e) {
if (e.which === 8) {
// added for demo to prevent browser address change
e.preventDefault();
$(this).css("background-color", "black");
}
});
$(".shape").keyup(function() {
$(this).css("background-color", "yellow");
});
.shape {
width: 40px;
height: 40px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shape" tabindex="0"></div>

jsFiddle

要监听任何按键事件,而不需要将焦点放在特定元素上,您可以将代码调整为以下内容:

$(document).keydown(function(e) {
if (e.which === 8) {
e.preventDefault();
$(".shape").css("background-color", "black");
}
});
$(document).keyup(function() {
$(".shape").css("background-color", "yellow");
});
.shape {
width: 40px;
height: 40px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shape"></div>

jsFiddle

关于javascript - jQuery - 改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54916588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com