如何使用箭头键创建可滚动的页面内容?

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

我只是尝试使用 HTML 和 JavaScript,但我对如何做到这一点感到有点困惑。

我想创建一个可以使用键盘上的箭头键滚动或按按钮滚动到下一页的页面。

这个想法是让内容展开,但通过使用箭头键,它将转到下一段内容,而无需重新加载网页。我已经尝试过一些东西,包括 AngularJS,但我宁愿将其硬编码而不是使用框架(除非没有框架会非常困难)

paint example

因此您可以看到按下了一个箭头按钮/箭头键,这将触发下一页。可以在多个 HTML 文件中完成此操作,还是在一个文件中完成所有操作并将每一页内容放在不同的 div 中会更好?

一旦我发现这一点,我就会寻求实现一个动画,这样当按下箭头时,您可以看到下一页与上一页重叠。

javascript html css web
2个回答
1
投票

尝试这样的事情

var selected = 2;

window.onkeyup = function(e) {
  if (e.key == 'ArrowRight') {
    right();
  } else if (e.key == 'ArrowLeft') {
    left();
  }
}

function left() {
  var section1 = document.getElementById('1');
  var section2 = document.getElementById('2');
  var section3 = document.getElementById('3');
  
  if (selected == 2) {
    section1.style.left = '0vw';
    section2.style.left = '100vw';
    section3.style.left = '200vw';
    
    selected = 1;
  } else if (selected == 3) {
    section1.style.left = '-100vw';
    section2.style.left = '0vw';
    section3.style.left = '100vw';
    
    selected = 2;
  }
}

function right() {
  var section1 = document.getElementById('1');
  var section2 = document.getElementById('2');
  var section3 = document.getElementById('3');
  
  if (selected == 1) {
    section1.style.left = '-100vw';
    section2.style.left = '0vw';
    section3.style.left = '100vw';
    
    selected = 2;
  } else if (selected == 2) {
    section1.style.left = '-200vw';
    section2.style.left = '-100vw';
    section3.style.left = '0vw';
    
    selected = 3;
  }
}
body, html {
  margin: 0px;
  font-family: Arial;
  overflow: hidden;
}

.header {
  width: calc(100vw - 32px);
  height: 10vh;
  padding: 16px;
  background-color: black;
  color: white;
  font-size: 32px;
  text-align: center;
}

.scrollale {
  width: 100vw;
  height: calc(90vh - 32px); /* For the padding of the header */
  overflow: hidden; /* Remove the scroll bar from the bottom */
}

.scroll {
  position: absolute;
  top: 40vh;
  font-size: 48px;
  user-select: none;
  z-index: 10;
}

.scroll:hover {
  cursor: pointer;
  color: grey;
}

.left {
  left: 16px;
}

.right {
  right: 16px;
}

.section {
  position: absolute;
  width: 100vw;
  height: calc(90vh - 32px); /* For the padding of the header*/
  font-size: 72px;
  text-align: center;
  transition: 0.5s;
}

.part1 {
  left: -100vw;
}

.part2 {
  left: 0vw;
}

.part3 {
  left: 100vw;
}
<div class="header">Header</div>
<div class="scrollable">
  <div class="scroll left" onclick="left()"><</div>
  <div id="1" class="section part1">Section 1</div>
  <div id="2" class="section part2">Section 2</div>
  <div id="3" class="section part3">Section 3</div>
  <div class="scroll right" onclick="right()">></div>
</div>

如果箭头键不起作用,请尝试先单击按钮(选择它)。

编辑

我关键的检测方法是使用

key
值,应该比较一致。


0
投票

对于块代码(即:code.org),您可以使用 if 语句。

if:按下箭头键 否则如果:单击了 Img.of.arrow 然后:移至页面...等

© www.soinside.com 2019 - 2024. All rights reserved.