无法使用jQuery为我的div设置绝对位置

时间:2011-12-18 04:47:23

标签: jquery css-position

@Purmou

嗨,请考虑以下html5文件。 div仍然位于0,0,边界也没有出现。我已尝试对随附的各种更改,但似乎无效。

非常感谢Purmou和所有其他人阅读本文的帮助。问候,sbguy

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Absolute Positioning Test</title>
<style type="text/css">
html, body {
    position:absolute; 
    top:0;
    left:0;
    margin:0px;
    padding:0px 0px 0px 0px;
    height:100%;
    width:100%;
}
div {
    margin:0px;
    padding:0px 0px 0px 0px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/JavaScript">
var A_height = 100;
var A_width = 100;
var A_top = 20;
var A_left = 20;
var B_height = 100;
var B_width = 100;
var B_top = 200;
var B_left = 200;
jQuery("#A").css({ 
    "position": "absolute",
    "width": A_width + "px",
    "height": A_height + "px",
    "top": A_top + "px",
    "left": A_left + "px",
    "border": "1px solid black",
    });
jQuery("#B").css({
    "position": "absolute",
    "width": B_width + "px",
    "height": B_height + "px",
    "top": B_top + "px",
    "left": B_left + "px",
    "border": "1px solid black",
    });
</script>
</head>
<body>
<div id="A">
<p>HELLO A</p>
</div>
<div id="B">
<p>HELLO B</p>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:9)

尝试使用:

jQuery("#div1A").css({
    "position":"absolute", 
    "top": $("#div1A").offset().top + "px",
    "left": $("#div1A").offset().left + "px",
});

编辑:您显然希望将变量div1A_topdiv1A_left设置为topleft CSS值:

jQuery("#div1A").css({
    "position":"absolute", 
    "top": div1A_top + "px",
    "left": div1A_left + "px",
});