因此,当您输入十六进制时,我会有一个页面,它将更改为该背景。问题是,由于某种原因,您需要先按空格键。我的问题是如何得到它,以便在初始加载时无需按空格就可以输入它?这是我的输入更改背景的代码

 $('.hex').keyup(function(){
      var a = $(this).val();
      $('#example').text(a);
      console.log(a);
      $('body').css('background', '#'+a);
});


Here's演示。在第一个框中输入一个十六进制。什么也不会发生,然后按空格键并输入另一个十六进制。

最佳答案

您需要将onkeyup事件处理程序注册代码放置在onkeydown事件处理程序之外。

这是onkeydown事件处理程序中的代码:

$(document).keydown(function(e) {
  if (e.keyCode == '32') {
     //...
     //you placed the onkeyup event handler registering code here
     //which is wrong
  }
}
//you should place the code here
$('.hex').keyup(function(){
  var a = $(this).val();
  $('#example').text(a);
  console.log(a);
  $('body').css('background', '#'+a);
});


Updated demo.

09-25 17:09
查看更多