jQuery - 用 DIV 跟随光标

新手上路,请多包涵

我如何使用 jQuery 跟随带有 DIV 的光标?

原文由 Peter 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 270
2 个回答

你不能用 DIV 跟随光标,但是你可以在移动光标时画一个 DIV

 $(document).on('mousemove', function(e){
    $('#your_div_id').css({
       left:  e.pageX,
       top:   e.pageY
    });
});

该 div 必须不浮动,因此应设置 position: absolute

原文由 jAndy 发布,翻译遵循 CC BY-SA 3.0 许可协议

为此,您不需要 jQuery。这是一个简单的工作示例:

 <!DOCTYPE html>
<html>
    <head>
        <title>box-shadow-experiment</title>
        <style type="text/css">
            #box-shadow-div{
                position: fixed;
                width: 1px;
                height: 1px;
                border-radius: 100%;
                background-color:black;
                box-shadow: 0 0 10px 10px black;
                top: 49%;
                left: 48.85%;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var bsDiv = document.getElementById("box-shadow-div");
                var x, y;
    // On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
                window.addEventListener('mousemove', function(event){
                    x = event.clientX;
                    y = event.clientY;
                    if ( typeof x !== 'undefined' ){
                        bsDiv.style.left = x + "px";
                        bsDiv.style.top = y + "px";
                    }
                }, false);
            }
        </script>
    </head>
    <body>
        <div id="box-shadow-div"></div>
    </body>
</html>

我选择了 position: fixed; 所以滚动不是问题。

原文由 hairy yuppie 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题