将鼠标放在div中 [英] Keep mouse inside a div

查看:68
本文介绍了将鼠标放在div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个说100px,100px尺寸的div, onmousedown 我想在这个div中移动一个对象并希望鼠标不要指向除div以外的任何其他地方我的对象放在div中。鼠标将恢复正常 onmouseup

I have a div of say 100px,100px dimensions, onmousedown I want to move an object inside this div and want the mouse should not point anywhere else except that div so that my object is placed in the div. Mouse will be back to normal onmouseup .

将鼠标放在那个div里面的javascript应该是什么?

What should be the javascript to keep the mouse inside that div only?

推荐答案

用Javascript控制鼠标位置是不可能的; 但是你可以控制你想要的对象...这里有一个简单的代码几乎这样做:

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>

这篇关于将鼠标放在div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆