jQuery - Changing Color

问题: Just new to learning some jQuery. I've been looking at some tutorials on w3schools. My aim is to change a shape color when I press a key. I can do this for a button but not...

问题:

Just new to learning some jQuery. I've been looking at some tutorials on w3schools. My aim is to change a shape color when I press a key. I can do this for a button but not a shape.

I'm using key code 8 which is backspace and am using this

$("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>

How would I do it for example with the following. I've tried several ways but can't seem to get it to work. Why won't changing the selector to the class name not work? Any tips are grateful. Thank you

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


回答1:

Your button natively accepts keyboard focus, whereas your div does not. Add this to .shape:

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

Demo

$(".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

To listen for any key event, without needing the focus to be on a specific element, you could adjust your code to the following:

$(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

  • 发表于 2019-03-01 03:02
  • 阅读 ( 138 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除