You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击Pause/Unpause Video按钮时如何阻止页面跳转至顶部?

问题解决:点击按钮时页面不再跳转顶部

问题原因

你使用的<a href="#">标签中,href="#"的默认行为是让页面跳转到顶部(锚点定位到页面顶端),所以即便点击时执行了暂停/播放视频的函数,浏览器仍会触发这个默认跳转动作,导致页面回到顶部。

解决方法

这里提供几种简单有效的修改方式:

方法1:阻止<a>标签的默认跳转行为

直接在onclick事件执行函数后添加return false;,就能阻止浏览器的默认跳转动作:

<a href="#" onclick="pauseVideo(); return false;" style="font-size: 35px; text-decoration: none" > Pause Video</a>
<a href="#" onclick="unpauseVideo(); return false;" style="font-size: 35px; text-decoration: none" > Unpause Video</a>

方法2:改用<button>标签(更推荐,语义化更好)

既然这些是操作按钮,用<button>标签更合适,它本身没有跳转的默认行为,只需调整样式匹配原有效果:

<td>
  <button onclick="pauseVideo()" style="font-size: 35px; border: none; background: none; text-decoration: none; cursor: pointer;">Pause Video</button>
</td>
<td>
  <button onclick="unpauseVideo()" style="font-size: 35px; border: none; background: none; text-decoration: none; cursor: pointer;">Unpause Video</button>
</td>

方法3:在JavaScript函数中阻止默认事件

修改函数,接收事件参数并调用preventDefault():

function pauseVideo(e){
  e.preventDefault();
  video.pause();
}

function unpauseVideo(e){
  e.preventDefault();
  video.play();
}

然后修改HTML里的调用,传入事件对象:

<a href="#" onclick="pauseVideo(event)" style="font-size: 35px; text-decoration: none" > Pause Video</a>
<a href="#" onclick="unpauseVideo(event)" style="font-size: 35px; text-decoration: none" > Unpause Video</a>

以上三种方法都能解决页面跳转顶部的问题,根据你的习惯选择即可。

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:41:20