jQuery - Follow the cursor with a DIV

前端 未结 3 1913
旧巷少年郎
旧巷少年郎 2020-11-28 21:04

How can I use jQuery to follow the cursor with a DIV?

相关标签:
3条回答
  • 2020-11-28 21:11

    You don't need jQuery for this. Here's a simple working example:

    <!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>
    

    I chose position: fixed; so scrolling wouldn't be an issue.

    0 讨论(0)
  • 2020-11-28 21:23

    You can't follow the cursor with a DIV, but you can draw a DIV when moving the cursor!

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

    That div must be off the float, so position: absolute should be set.

    0 讨论(0)
  • 2020-11-28 21:32

    This works for me. Has a nice delayed action going on.

    var $mouseX = 0, $mouseY = 0;
    var $xp = 0, $yp =0;
    
    $(document).mousemove(function(e){
        $mouseX = e.pageX;
        $mouseY = e.pageY;    
    });
    
    var $loop = setInterval(function(){
    // change 12 to alter damping higher is slower
    $xp += (($mouseX - $xp)/12);
    $yp += (($mouseY - $yp)/12);
    $("#moving_div").css({left:$xp +'px', top:$yp +'px'});  
    }, 30);
    

    Nice and simples

    0 讨论(0)
提交回复
热议问题