在表单中写入时如何停止 preventDefault()

How to stop the preventDefault() when write in the form

我建了一个简单的博客,这个博客有视频和评论部分21=] 使 space 在单词之间 space 在写入时不起作用,视频仍在播放和暂停。

如何在写评论时阻止或停止此功能

JavaScript 文件

        window.onkeydown = vidCtrl;

    function vidCtrl(e){
      const vid = document.querySelector('video')
      const key = e.code;

      if (key === 'ArrowLeft') {
    vid.currentTime -= 5;
    if (vid.currentTime < 0) {
      vid.pause();
      vid.currentTime = 0;
    }
  } else if (key === 'ArrowRight') {
    vid.currentTime += 5;
    if (vid.currentTime > vid.duration) {
      vid.pause();
      vid.currentTime = 0;
    }
  } else if (key === 'Space') {
    e.preventDefault();
    if (vid.paused || vid.ended) {
      vid.play();
    } else {
      vid.pause();
    }


  }
    }

评论表

   <form id="myForm" method="post">
  {{ comment_form.as_p }}
  {% csrf_token %}
  <button type="submit" class="btn btn-primary btn-lg btn-block" name="button">Submit</button>
</form>
<script>

您可以使用 document.activeElement 检查活动元素。如果活动元素是您的 vid,则继续执行事件处理程序。

window.onkeydown = vidCtrl;

function vidCtrl(e) {
  const vid = document.querySelector('video');
  const key = e.code;

  if (document.activeElement === vid) {
    if (key === 'ArrowLeft') {
      vid.currentTime -= 5;
      if (vid.currentTime < 0) {
        vid.pause();
        vid.currentTime = 0;
      }
    } else if (key === 'ArrowRight') {
      vid.currentTime += 5;
      if (vid.currentTime > vid.duration) {
        vid.pause();
        vid.currentTime = 0;
      }
    } else if (key === 'Space') {
      e.preventDefault();
      if (vid.paused || vid.ended) {
        vid.play();
      } else {
        vid.pause();
      }
    }
  }
}

使用 e.target 检查目标元素然后 return 如果当前元素是您的评论框

演示在这里不起作用,请尝试 jsfiddle

window.onkeydown = vidCtrl;

function vidCtrl(e) {
  console.log(e.target.localName);
  if(e.target.localName == "textarea");
     return
  
  const vid = document.querySelector('video')
  const key = e.code;
  
  if (key === 'ArrowLeft') {
    vid.currentTime -= 5;
    if (vid.currentTime < 0) {
      vid.pause();
      vid.currentTime = 0;
    }
  } else if (key === 'ArrowRight') {
    vid.currentTime += 5;
    if (vid.currentTime > vid.duration) {
      vid.pause();
      vid.currentTime = 0;
    }
  } else if (key === 'Space') {
    e.preventDefault();
    if (vid.paused || vid.ended) {
      vid.play();
    } else {
      vid.pause();
    }
  }
}
<video width="400" controls>
  <source src="https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4" type="video/mp4">
</video>

<textarea style="width:80%; height:60px"></textarea>