繁体   English   中英

Javascript-如何使用键盘键显示和隐藏元素?

[英]javascript - How do I show and hide an element using keyboard keys?

我刚刚提出了一个提问者申请。 有一个下一个和上一个功能,以及一个带有javascript的按钮,我可以在其中隐藏和显示问题。

我想从下一个和上一个示例创建一个快捷键:

向左箭头->将转到上一个问题向右箭头->将转到下一个问题

以下是我的脚本的摘录:

<form>
  <div id="question1" class="cont active"> </ div>
  <div id="question2" class="cont hide"> </ div>
  <div id="question3" class="cont hide"> </ div>
</form>

当我按向右箭头时,则div#question应该隐藏并且div#question2应该处于活动状态,而当我按向左箭头时则相反。 我被困住了,我一直在寻找参考资料,希望有人能提供帮助。

要捕获按键,您可以尝试:

document.onkeydown = function(e){

  if(e.key == "ArrowLeft" && e.target == document.body){
    //left arrow
  }
  if(e.key == "ArrowRight" && e.target == document.body){
    //right arrow
  }
}

隐藏您可以使用的元素,例如:

document.getElementById('question1').style.display = "none";

并再次显示:

document.getElementById('question1').style.display = "block";

箭头键可以通过keydown捕获。

var activeQuestion = 1;
document.addEventListener( 'keydown', function(ev) {
    if( ev.key === "ArrowLeft" && activeQuestion > 1 ){
      hide( 'question' + activeQuestion ); // hide current element
      show( 'question' + --activeQuestion ); // show next element
    }
    else if(  ev.key === "ArrowRight" && activeQuestion < 3  ){
      hide( 'question' + activeQuestion );
      show( 'question' + ++activeQuestion );
    }
} )

function hide ( elementId ){
  let el = document.getElementById(elementId);
  el.className = el.className.replace( 'active', 'hide' );
}
function show( elementId ){
  let el = document.getElementById(elementId);
  el.className = el.className.replace( 'hide', 'active' );
}

例如: https : //jsfiddle.net/634vma8r/单击矩形区域以工作,然后按->和<-。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM