首页 > 解决方案 > 使用按键 jquery/javascript 更改一个 div 的颜色

问题描述

我想通过单击“1”键来更改一个 div 的颜色。我有一堆视频正在播放,当你点击“1”时,某个视频开始播放。我想创建一个看起来像控制面板的东西,这样当你点击“1”时,视频会打开(我在javascript中使用了按键),但当我按下“1”时也会改变我的div的颜色

HTML

</head>
<body>

<div class="intro">Press The Number Keys and Q W E To Activate Video
</div>

<div id="one">1</div>

JAVASCIPT JQUERY

$(document).ready(function() {
  $(document).keypress(function(event) {
    if (event.which === 49) {
      $("#one").css('background-color'),("#00ffff");
    }
  });
 });


document.onkeypress = function(e) {
  console.log(e)
  if (e.key === "1" ) {
   var vid = document.getElementById('vid');
   vid.paused ? vid.play() : vid.pause();
   var vid = document.getElementById('vid').style.opacity = '1';

  } else if (e.key === "2" ) {
   var cami = document.getElementById('cami');
   cami.paused ? cami.play() : cami.pause(); 
   var cami = document.getElementById('cami').style.opacity = '1';

  }

标签: javascriptjqueryhtmlbackground-colorkeypress

解决方案


像这样的东西应该能让你到达那里。只是将背景颜色更改逻辑沙盒化。

<div class="intro">Press The Number Keys and Q W E To Activate Video
</div>


<div id="changeExample">This is a test</div>

document.onkeypress = function(e) {
  console.log(e)
  if (e.key === "1" ) {
        if( $("#changeExample").hasClass("red")  ){

            $("#changeExample").removeClass("red").addClass("pink").css("background-color", "pink");

        }
        else if( $("#changeExample").hasClass("pink") ){
            $("#changeExample").removeClass("pink").addClass("red").css("background-color", "red");
        }
        else{
            $("#changeExample").addClass("red").css("background-color", "red");
        }

  }
}

推荐阅读