在带有event.code的switch语句中使用JavaScript运算符

问题描述 投票:0回答:1

我有一个switch语句,在该语句中,我尝试将键盘快捷键映射到水平的整页滚动:

  • 空格键Page Down向右箭头向前滚动
  • Page UpLeft Arrow滚动向后
  • HomeUp Arrow转到开头页面的]]
  • End
  • Down Arrow滚动到末尾页面的]]

    这是我的尝试,不起作用:

switch (event.code) {
  case "Space" || "PageDown" || "ArrowRight": {
    scrollAmount += window.innerWidth
    break
  }
  case "PageUp" || "ArrowLeft": {
    scrollAmount -= window.innerWidth
    break
  }
  case "Home" || "ArrowUp": {
    scrollAmount = 0
    break
  }
  case "End" || "ArrowDown": {
    scrollAmount = container.scrollWidth
    break
  }
}

在这种情况下如何正确使用运算符?

[我有一个switch语句,在其中我尝试将键盘快捷键映射到水平的整页滚动:空格键或Page Down或向右箭头向前滚动Page Up或向左箭头向后滚动...

javascript ecmascript-6 switch-statement
1个回答
1
投票

您应分别指定每种情况:

switch (event.code) {
  case "Space":
  case "PageDown":
  case "ArrowRight": {
    scrollAmount += window.innerWidth
    break
  }
  case "PageUp":
  case "ArrowLeft": {
    scrollAmount -= window.innerWidth
    break
  }
  case "Home":
  case "ArrowUp": {
    scrollAmount = 0
    break
  }
  case "End":
  case "ArrowDown": {
    scrollAmount = container.scrollWidth
    break
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.