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

时间:2018-11-24 16:50:29

标签: javascript html css web

我只是在尝试HTML和JavaScript,因此我对如何做到这一点感到有些困惑。

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

想法是使内容散布,但是使用箭头键,它将转到下一部分内容,而无需重新加载网页。我已经尝试了包括AngularJS在内的一些方法,但是我宁愿对其进行硬编码而不使用框架(除非没有框架非常困难)

paint example

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

一旦我发现我想实现一种动画,以便在按下箭头时可以看到下一页与上一页重叠。

1 个答案:

答案 0 :(得分: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值的密钥检测方法,该值应该更一致。