javascript - 在表单中写入时如何停止 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>
解决方案
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>
推荐阅读
- typo3 - 如何在站点包中存储 TYPO3 站点配置?
- c++ - 是否可以根据数据成员的类型确定类型的大小
- python - 在函数中查找 Pandas 数据帧的长度
- computer-vision - 是否可以在 PyTorch 中“屏蔽”不需要的输入和特征图,以便 PyTorch 简单地忽略它们?
- powershell - PowerShell 中的 -UseDefaultCredential 与 -Credential(401 错误)
- mysql - MySQL if else 语句与多查询
- sql - 在 shell 脚本中编写循环以读取 HIVE Select 的输出
- shopify - 在 Shopify Liquid 中计算特定邮政编码的今天订单
- c - Printf 输出顺序错误 - 我该如何解决?
- reactjs - React Redux rest-api 中的空道具 Object.keys