0

我有两个简单的 div,其中一个包含在另一个中

div#numero{
    position:absolute;
    background-color:#ff3324;
    border-style: solid;
    border-width: 2px;
    width:30px;
    height:30px;
    font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
    font-size:1em;
    line-height: 30px;
    text-align:center;
    margin-left:0;
    margin-right:0;
};

div#cont{
    position:relative;
    border-style: solid;
    border-width: 2px;
    width:500px;
    height:500px;
    margin-left:auto;
    margin-right:auto;
    padding:0;
}

我想移动容器内的第一个内部 div

    <div id = "cont" onmousemove = "moveDiv()">
        <div id = "numero">
            1        
        </div>
     </div>

moveDiv 简单的地方

function moveDiv()
{
    var e = document.all["numero"]
    x = window.event.clientX ;
    y = window.event.clientY ;

    e.style.left = x +"px";
    e.style.top = y +"px";


}

该代码无法按我的意愿工作。鼠标所在的位置和内部 div (numero) 移动的位置之间存在很大的偏移。我还想限制容器 div 内的移动。一些帮助将不胜感激。

谢谢。

4

1 回答 1

0

http://jsfiddle.net/enHmy/

在您的 html 代码后添加以下代码

document.getElementById('cont').onmousemove=moveDiv;

然后你的功能应该是:

function moveDiv(e){
    if(!e){e=window.event;}
    var el = document.getElementById('numero');
    x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2;
    y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2;

    el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px";
    el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px";
}

但是让我们分析一下您的功能:

你为什么用document.all["numero"]?那很老了,不能在兼容的浏览器上运行,现在它是document.getElementById('numero');.

然后你使用window.event. 这适用于 IE,但您应该传递一个参数e(事件),如果e未定义(它是旧的 IE),我们将其设置为window.event.

当你关闭一个 CSS 规则时,不要在}.

编辑:

如果滚动页面,numero则定位不正确。

在http://jsfiddle.net/enHmy/1/中修复:

function moveDiv(e){
    if(!e){e=window.event;}
    var el = document.getElementById('numero');
    x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2+getScroll('Left');
    y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2+getScroll('Top');

    el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px";
    el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px";
}
function getScroll(dir){
    return Math.max(document.body["scroll"+dir]||0,document.documentElement["scroll"+dir]||0);
}
于 2012-08-19T01:02:15.523 回答