zub*_*uba 10 javascript css jquery dom position
第一个div是'#icon-selection-menu'条形,它的空闲位置是绝对的top:0px和left:0px.所以它出现在内容div里面的左上角.
在内容div孩子的深处,我得到了其他div,实际上是'.emoticon-button'.他们的位置在他们的父母内部相对.按下这样的按钮,我想将第一个div放在按钮上方,将其底部边框调整到按钮的顶部边框.
我怎样才能获得顶部和左侧值来设置$('#icon-selection-menu').top和$('#icon-selection-menu').left?
bfa*_*tto 21
jQuery 1提供.offset()了获取相对于文档的任何元素的位置.由于#icon-selection-menu已经相对于文档定位,您可以使用:
var destination = $('.emoticon-button').offset();
$('#icon-selection-menu').css({top: destination.top, left: destination.left});
Run Code Online (Sandbox Code Playgroud)
$('#icon-selection-menu')将被放置在左上角$('.emoticon-button').
(1)jQuery假设由于$在问题中的使用.
您可以使用offsetTop和offsetLeft获取div的顶部和左侧位置
例如:`
$('#div-id').offset().top;
$('#div-id').offset().left;
Run Code Online (Sandbox Code Playgroud)
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";
Run Code Online (Sandbox Code Playgroud)
当然,您可以向该系统添加单位,例如 px 或其他单位。请注意,我上面所做的只是一个示例,适用于两个带有 ID 的独立元素,而不是类。代码的前两行将根据您的代码而有所不同。该元素iconselect是我要对齐的元素,该元素emoticonbtn是您按下以使其iconselect出现的按钮。代码中最重要的部分总结如下:
elementtomove.offsetTop; //distance from top of screen
elementtomove.offsetLeft; //distance from left of screen
Run Code Online (Sandbox Code Playgroud)
希望这对那些不愿意使用JQUERY的人有帮助!