首页 > 解决方案 > 在表单中写入时如何停止 preventDefault()

问题描述

我建立了一个简单的博客,这个博客有视频和评论部分无法在写入中工作,视频仍在播放和暂停。

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

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>

标签: javascriptangularjsajaxreact-native

解决方案


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

演示在这里不起作用,请尝试使用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>


推荐阅读