javascript - 使用绝对将元素放在其他元素内。元素是 sibling

标签 javascript jquery css

我正在尝试使用绝对定位将元素“inner”与另一个 div“outer”的右上角齐平。 “内部”元素不是“外部”的子元素。因此,我需要使用 js 查找“外部”的定位并使用它。

但是,结果并不完全正确:

编辑:我无法重置正文 div 的边距/填充/相对值。 body 中还有其他元素。

http://jsfiddle.net/BZBSF/1/

#wrapper{background:red;
         width:100px;
         height:100px;}

#inner{
    position:absolute;
    background:green;
    width:50px;
    height:100px;
    margin:0;padding:0;
}

#body{position:relative;}

<div id = "body">
    <div id = "wrapper"></div>
    <div id = "inner"></div>    
</div>

var rect = document.getElementById("wrapper").getBoundingClientRect();

$("#inner").css({ 'top': String($(window).scrollTop()+rect.top)+"px" });

width_inner = $("#inner").width();

$("#inner").css({ 'left': String($(window).scrollLeft()+rect.right-width_inner)+"px" });

最佳答案

在 body 元素上设置边距和填充。

body{
    margin: 0;
    padding: 0;    
}

FIDDLE

或者如果没有具体原因body:relative;删除它。

FIDDLE

推荐第二种

关于javascript - 使用绝对将元素放在其他元素内。元素是 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783430/

相关文章:

javascript - 使用现有函数的输出作为对象属性

javascript - 加载不同网站的 html

html - 如何避免跨页面拆分 HTML 中的 DIV

javascript - 查询 flickr api

css - 将 SASS 变量设置为 CSS3 变量会导致 Bootstrap 4 出错

javascript - 我的 javascript(用于随机化 css3 动画延迟)不会在 IE 10 和 Opera 中触发...包含 Jsfiddle

javascript - 在 D3.js 中过渡旭日形

javascript - 在 BIRT 中显示修改后的参数值

javascript - 类型错误 : Cannot read property 'exp' of undefined

Javascript全局数组对象无法读取