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

如何限制鼠标悬停时随机移动的Skip Intro按钮仅在视频帧内?

实现限制在视频范围内移动的「Skip Intro」按钮

要让按钮仅在视频帧内随机移动,关键是获取视频元素的位置与尺寸,计算出按钮可移动的坐标范围,再在该范围内生成随机位置。以下是修改后的完整实现:

核心思路

  • 获取视频元素的边界信息(通过getBoundingClientRect()方法)
  • 计算按钮可移动的X轴范围:视频左侧坐标 到 (视频右侧坐标 - 按钮自身宽度)
  • 计算按钮可移动的Y轴范围:视频顶部坐标 到 (视频底部坐标 - 按钮自身高度)
  • 在上述范围内生成随机坐标,确保按钮完全处于视频帧内部

修改后的代码

JavaScript

var button = document.querySelector(".button");
var videoFrame = document.querySelector("iframe");

function randomizePosition() {
  // 获取视频元素的位置和尺寸
  const videoRect = videoFrame.getBoundingClientRect();
  // 获取按钮自身的尺寸
  const buttonRect = button.getBoundingClientRect();
  
  // 计算可移动的X范围:从视频左侧到(视频右侧 - 按钮宽度)
  const maxX = videoRect.right - buttonRect.width;
  const randomX = Math.random() * (maxX - videoRect.left) + videoRect.left;
  
  // 计算可移动的Y范围:从视频顶部到(视频底部 - 按钮高度)
  const maxY = videoRect.bottom - buttonRect.height;
  const randomY = Math.random() * (maxY - videoRect.top) + videoRect.top;
  
  button.style.left = randomX + "px";
  button.style.top = randomY + "px";
}

// 初始位置设置
randomizePosition();

// 鼠标悬停时切换位置
button.addEventListener("mouseenter", randomizePosition);

CSS

.button {
  display: inline-block;
  padding: 20px;
  position: fixed;
  font-family: Arial, Helvetica, sans-serif;
  border: solid 3px darkgrey;
  /* 增加指针样式,提示可交互 */
  cursor: pointer;
}

HTML

<div class='button'>SKIP INTRO</div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/g_4aEFYj3QA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"></iframe>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:43:17