Keep mouse inside a div

╄→гoц情女王★ 提交于 2019-12-05 05:40:41
Elieder

It's not possible to control mouse position with Javascript; but you can take his position to control the object that you want... here a simple code that almost do this:

<html>
<body>
<div id="divID" style="width: 100px; height: 100px; position: absolute; left: 250px; top: 300px; background: #000"></div>
<div id="divChild" style="width: 20px; height: 20px; color: #f00; position: absolute; background: #f00;"></div>
</body>
<script>
var div = document.getElementById("divID");
var divChild = document.getElementById("divChild");

mousepressed = 0;

function handleMyMouseMove(e) {
    var mouseX = e.clientX;
    var mouseY = e.clientY;
    if(mousepressed) {
        divChild.style.left = mouseX + "px";
        divChild.style.top = mouseY + "px";
    }
}

function handleMyMouseDown(e) { mousepressed = 1; }
function handleMyMouseUp(e) { mousepressed = 0; }

div.addEventListener("mousemove", handleMyMouseMove, false);
div.addEventListener("mousedown", handleMyMouseDown, false);
window.addEventListener("mouseup", handleMyMouseUp, false);
</script>
</html>
Jim Blackler

Impossible sadly... or happily if you think what some adverts might do with it.

Edit: found this discussion, where someone suggests a novel workaround Move Mouse Cursor Javascript

miguelv

Like the other guys say you can't constraint the mouse cursor to a specific area. But maybe that is not what you want. Look at this jQuery UI demo: Constrain Movement. It achieves the desired effect by keeping the inner object inside the parent object (see box saying "I'm contained within my parent").

<div class="draggable ui-widget-content">
<p id="draggable5" class="ui-widget-header">I'm contained within my parent</p></div>

<script>
$(function() {
    $( "#draggable5" ).draggable({ containment: "parent" });
});
</script>

if you want a creative solution, heres one that youl find very creative:

1: use [element].requestPointerLock()
2: create a new image of a mouse cursor. (here's one you might like)
3: create 2 new variables x and y, and lock the image position to them.
4: write:

document.addEventListener('mousemove', function(){
     x += window.movementX;
     y += window.movementY;
});

5: enter some if statements to keep the mouse image inside the element. make sure to keep the if statements' inside the eventlistener above:

document.addEventListener('mousemove', function(){
     x += window.movementX;
     y += window.movementY;

     if(x < parseFloat(element.style.left)){
            x = parseFloat(element.style.width);
     }
     if(x > parseFloat(element.style.left) + parseFloat(element.style.width)){
            x = parseFloat(element.style.width) + parseFloat(element.style.width);
     }
     if(y < parseFloat(element.style.top)){
            y = parseFloat(element.style.top);
     }
     if(y > parseFloat(element.style.top) + parseFloat(element.style.height)){
            y = parseFloat(element.style.top) + parseFloat(element.style.height);
     }
});

make sure to replace "element" with the name of the variable storing your element if you intend on using this exact code.

and dont forget to update the position of your element by assigning x and y to its position every time you use it. try the code below. it has all these steps implemented and tested. just click the screen to start, and press [Esc] to turn it off.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>New webpage</title>
    </head>
    <body>
        <img id="div" src="https://b.sccpre.cat/mypng/small/51-    518482_mouse-svg-cursors-mac-transparent-background-mouse-cursor.png" alt="hi"     style="position: absolute; width: 20px; height: 20px;">

        <div id="cage" style="width: 200px; height: 200px; background-    color: lightgray; left: 0px; top: 0px;">


        </div>

    <h1 id="tx">click to start</h1>


    </body>
    <script>
        var d = document.getElementById('div');
        var tx = document.getElementById('tx');
            document.addEventListener('click', function(){
var txt = tx.textContent;
        if(txt === "click to start"){
                    d.requestPointerLock();
            tx.textContent = "click to stop";
        }
        if(txt === "click to stop"){
            document.exitPointerLock();  
            tx.textContent = "click to start";
        }    
    });

        var x = 0;
        var y = 0;


        var cage = document.getElementById('cage');

        document.addEventListener("mousemove", function(e){
            x += e.movementX;
            y += e.movementY;

            if(x < parseFloat(cage.style.left)){
                x = parseFloat(cage.style.left);
            }
            if(x > parseFloat(cage.style.left) +         parseFloat(cage.style.width)){
                x = parseFloat(cage.style.left) + parseFloat(cage.style.width);
            }
            if(y < parseFloat(cage.style.top)){
                y = parseFloat(cage.style.top);
            }
            if(y > parseFloat(cage.style.top) + parseFloat(cage.style.height)){
                y = parseFloat(cage.style.top) + parseFloat(cage.style.height);
            }
            d.style.left = x + 'px';
            d.style.top = y + 'px';

        });

    </script>
</html>

you can't control the mouse position with javascript, the only thing you can do is to read the mouse position and react to it. Maybe you can move the div so that it's always under the mouse?

You cannot constrain the mouse.

But if you want to constrain another object (for instance, one that is being dragged by the mouse) you can. But you will need to provide more info on what and how you try to do..

That's completely impossible, and you should be grateful for it. Your mouse is your system's primary input, and if browsers were able to control or commandeer it there is virtually nothing a site couldn't do.

It is possible, however, to constrain a dragged object within another DIV - jQueryUI's draggable(), for instance, makes this incredibly easy.

I seem to have found a workaround for my project.

I did the following:
1. Using CSS, disable the default click event of every element in your document.
2. For the body: cursor:none;.
3. Have a position:fixed; div function as a pseudo mouse.
4. Use jQuery to track mouse velocity and thus poisition your pseudo mouse.
5. Work from there.

Warning: Your real mouse will still function normally outside your webpage. My purpose did not require clicking any element and thus worked.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!