如何使用javascript将div放在另一个div的顶部?

第一个div是'#icon-selection-menu'栏,它的空闲位置是绝对的top:0pxleft:0px 。 所以它出现在内容div内的左上角。

在内容div孩子的深处,我得到了其他div,实际上是’.emoticon-button’。 他们的位置在他们的父母内部相对。 按下这样的按钮,我想将第一个div放在按钮上方,将其底部边框调整到按钮的顶部边框。

我如何获得顶部左侧值来设置$('#icon-selection-menu').top$('#icon-selection-menu').left

jQuery 1提供.offset()来获取任何元素相对于文档的位置。 由于#icon-selection-menu已经相对于文档定位,您可以使用:

 var destination = $('.emoticon-button').offset(); $('#icon-selection-menu').css({top: destination.top, left: destination.left}); 

$('#icon-selection-menu')将放置在$('.emoticon-button')左上角。

(1)jQuery假设由于在问题中使用了$

您可以使用offsetTop和offsetLeft获取div的顶部和左侧位置

例如:`

 $('#div-id').offset().top; $('#div-id').offset().left; 

Javascript有@bfavaretto提到的内置版本。 它比Jquery版本长一点,但像我这样不使用Jquery的人可能需要它。

 var iconselect = document.getElementById("icon-selection-menu"); var emoticonbtn = document.getElementById("emoticon-button"); var oTop = emoticonbtn.offsetTop; var oLeft = emoticonbtn.offsetLeft; iconselect.style.top = oTop; iconselect.style.left = oLeft; iconselect.style.position = "absolute"; 

当然,您可以在此系统中添加单位,例如px或其他内容。 请注意,我上面所做的只是一个例子,是两个带有ID的单独元素,而不是类。 代码的前两行将根据您的代码而有所不同。 元素iconselect是我想要对齐的元素,元素emoticonbtn是你按下按钮以显示iconselect 。 代码中最重要的部分总结如下:

 elementtomove.offsetTop; //distance from top of screen elementtomove.offsetLeft; //distance from left of screen 

希望这能帮助那些不愿意使用JQUERY的人!

获取’.emoticon-button’位置(左,上)。 然后将其应用于’#icon-selection-menu’。 顶部和左侧会有一些调整以与表情符号对齐。

你可以使用下面的jquery获取元素的位置

 var position=$('#icon-selection-menu').position(); var left=position.left; var right=position.right 

点击该按钮,您可以使用以上位置

 $("#ID").live("click",function(){ $('.emoticon-button').animate({left:left,right:right}); });