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

如何实现按X键切换半圆跟随/停止跟随鼠标且停止时保留当前角度

原代码失效原因
  • 你定义的状态变量没有和mousemove事件的执行逻辑关联,状态切换不会影响旋转逻辑运行
  • 你在自定义函数中修改的Null是局部变量,作用域仅限函数内部,不会影响全局事件监听逻辑
  • 没有绑定键盘事件监听,无法检测到X键的按下动作
修复后完整代码
<div class="Null"></div>
<script>
    document.querySelector("body").addEventListener('mousemove', Null);
    document.querySelector("body").addEventListener('keydown', toggleFollow);
    // 跟随开关,默认开启
    var isFollowEnabled = true;

    function Null(){
        // 开关关闭时直接返回,不执行旋转逻辑
        if(!isFollowEnabled) return;
        var Null = document.querySelectorAll(".Null");
        Null.forEach(function (Null) {
            let x = (Null.getBoundingClientRect().left) + (Null.clientWidth / 2);
            let y = (Null.getBoundingClientRect().top) + (Null.clientHeight / 2);
            let radian = Math.atan2(event.pageX - x,event.pageY - y);
            let rot = (radian * (180 / Math.PI) * -1) + 270;
            Null.style.transform = "rotate("+ rot +"deg)";
        })
    }

    function toggleFollow(e) {
        // 匹配X键,不区分大小写
        if(e.key.toLowerCase() === 'x') {
            isFollowEnabled = !isFollowEnabled;
        }
    }
</script>
<style>
 /*Da EyE!?*/
  .Null {
  pointer-events: none;
  position: fixed;
  height: 0px;
  width: 0px;
  padding: 120px;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  max-width: 100%;
  max-height: 100%;
  overflow: auto;
  border-radius: 50%;
  border: 10px solid rgb(0, 0, 0, 0.21);
  border-bottom-color: transparent;
  border-top-color: transparent;
  border-right-color: transparent;
  }
  .Null:before {
  content: "";
  position: fixed;
  left: 0px;
  right: 0px;
  top: 0px;
  bottom: 0px;
  border: 10px solid rgb(0, 0, 0, 0.1);
  border-bottom-color: transparent;
  border-top-color: transparent;
 border-right-color: transparent;
  border-radius: 50%;
 }
</style>
实现说明
  • 旋转函数开头新增状态判断,开关关闭时直接终止函数执行,半圆就会停留在当前角度
  • 新增键盘按下事件监听,检测到按下X键时翻转开关状态,实现暂停/恢复跟随切换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:54:03