如何获取'droppable'的offset()。left和offset()。top而不使用jquery,使用原始javascript

时间:2010-10-04 08:56:03

标签: javascript jquery position offset

由于某种原因,我不能使用jquery。

这是我的代码:

<!DOCTYPE html>
<html>
<head>
</head>
<body >
<style type="text/css">
#draggable
        {
            position: absolute;
            width: 100px;
            height: 100px;
            padding: 0.5em;
            float: left;
            margin: 10px;
            border: 1px solid #DDDDDD;
            color: #333333;
            background: #F2F2F2;
            cursor: move;
            z-index:10;
        }
        #droppable
        {
            width: 150px;
            height: 150px;
            padding: 0.5em;
            float: left;
            margin: 10px;
            border: 1px solid #E78F08;
            color: #FFFFFF;
            font-weight: bold;
            background: #F6A828;
            overflow: hidden;
        }
</style>
<p>
    Eos an invidunt dignissim liberavisse, no paulo alterum vix, mei causae vivendum
    te. Discere omittam ea sed. Est ex mutat aeque discere. Omnes tincidunt pro ea.
    Mentitum expetenda reprehendunt vis id, duo natum adhuc ut. Malis partiendo id duo,
    feugait iudicabit consequuntur at eum.
</p>
<div id="droppable">
    <p>
        Drop here.
    </p>
</div>
<p>
    Ea eam audire antiopam, agam consulatu patrioque no nec. Sea simul insolens ne,
    vero scribentur duo ut. Te mel dico choro virtute. Mel ex sumo omnes.
</p>


<p>
    Eos an invidunt dignissim liberavisse, no paulo alterum vix, mei causae vivendum
    te. Discere omittam ea sed. Est ex mutat aeque discere. Omnes tincidunt pro ea.
    Mentitum expetenda reprehendunt vis id, duo natum adhuc ut. Malis partiendo id duo,
    feugait iudicabit consequuntur at eum.
</p>
<p>
    Ea eam audire antiopam, agam consulatu patrioque no nec. Sea simul insolens ne,
    vero scribentur duo ut. Te mel dico choro virtute. Mel ex sumo omnes.
</p>
<div id="draggable" >
    <p>Drag me to my target</p>
</div>
<script>
function id(id){
    return document.getElementById(id)
}
console.log(id('droppable').offsetWidth,id('droppable').offsetTop)
id('draggable').style.left =id('droppable').offsetWidth+'px'
id('draggable').style.top = id('droppable').offsetTop+'px'

</script>
</body>
</html>

这是演示http://jsfiddle.net/6H5Yj/

所以如何设置'draggable's left Equal the'droppable's left,top Equal top,

感谢

1 个答案:

答案 0 :(得分:0)

var bound = id('droppable').getBoundingClientRect();

var x= bound.left,y= bound.top 

id('draggable').style.left =x+'px'
id('draggable').style.top = y+'px'