向上翻页,向下翻页,向上和向下键在我的页面上不起作用

时间:2018-08-06 18:59:37

标签: javascript

我正在制作作品集以展示我的项目。因此,当有人单击菜单中的Project 1时,新的div(div#project1)将像新页面一样从左侧滑入以显示Project 1。

问题

  1. 向上,向下,向上和向下箭头在此div(div#project1)上不自动起作用。
  2. 我需要先单击div(div#project1),然后才能使用键盘滚动。

如何使其自动?寻找javascript答案!谢谢

function project() {
  document.getElementById("project1").toggleClass('show');
  document.getElementById('project1').addEventListener('click', function() {
    this.classList.toggle('focus'); // or whatever...
    this.focus();
  });
}

HTMLElement.prototype.addClass = function(string) {
  if (!(string instanceof Array)) {
    string = string.split(' ');
  }
  for (var i = 0, len = string.length; i < len; ++i) {
    if (string[i] && !new RegExp('(\\s+|^)' + string[i] +
        '(\\s+|$)').test(this.className)) {
      this.className = this.className.trim() + ' ' + string[i];
    }
  }
}

HTMLElement.prototype.toggleClass = function(string) {
  if (string) {
    if (new RegExp('(\\s+|^)' + string + '(\\s+|$)').test(this.className)) {
      this.className = this.className.replace(new RegExp('(\\s+|^)' + string +
        '(\\s+|$)'), ' ').trim();
    } else {
      this.className = this.className.trim() + ' ' + string;
    }
  }
}

HTMLElement.prototype.removeClass = function(string) {
  if (!(string instanceof Array)) {
    string = string.split(' ');
  }

  for (var i = 0, len = string.length; i < len; ++i) {
    this.className = this.className.replace(new RegExp('(\\s+|^)' + string[i] +
      '(\\s+|$)'), ' ').trim();
  }
}
.project {
  position: fixed;
  top: 0;
  width: 100vw;
  transition: all .5s;
  z-index: 100;
  left: 100vw;
  background: #fff;
  overflow-y: scroll;
  bottom: 0;
}

.show {
  left: 0vw!important;
}
<div id="menu">
  <h2 onclick="project()">Project 1</h2>
</div>

<div id="project1" class="project" onclick="project()">
  <h1>Project 1</h1>
  <center>
    <img src="x.png">
  </center>
</div>

1 个答案:

答案 0 :(得分:1)

您需要在内部focus侦听器回调之外执行click方法。并且当您隐藏项目详细信息时,最好从中删除焦点:

function project() {
    const proj = document.getElementById("project1");
    proj.classList.toggle('show');
    proj.addEventListener('click', function() {
        this.classList.toggle('focus');
        this.blur(); // Remove focus
    });
    proj.focus(); // Set the focus on the project details that just appeared.
}