日期:2014-05-16  浏览次数:20309 次

js下marginLeft的问题
在一个DIV元素内动态创建两个或多个img图片,想把这些图片放在同一个位置,即marginLeft和marginTop设为一样的值,但实现中发现后面的marginLeft为相对前一个img的距离,而不是相对父元素的值。

img图片我用的是position:absolute, DIV的position设为relative; 

应该怎么实现呢?就是所有图片的位置均只相对于DIV父元素而言就可以。

------解决方案--------------------
定位的位置设置,是top和left,bottom和right

定位的看下:http://www.w3school.com.cn/css/pr_class_position.asp

你设置的marginTop和marginLeft,是外边距。
http://www.w3school.com.cn/css/css_margin.asp

赶紧补基础知识。


------解决方案--------------------
你直接绝对定位上去不行吗  不很明白你的意思
------解决方案--------------------
这里,
把你的marginLeft改成left,
marginTop改成top。

------解决方案--------------------
3楼  +1~
------解决方案--------------------

position:absolute;
top:0px;
left:0px;
margin-left:10px;
margin-top:10px;

这个效果 可能就是 楼主想要的
------解决方案--------------------
给个你的代码呗!!!
------解决方案--------------------
有用,只是margin-top你设的太小,你自己没发觉。
#p1c   top:30px;   margin-top:50px;
http://www.w3schools.com/css/css_boxmodel.asp

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#p1 {
width:200px;
height:150px;
background-color:#ee9;
position:relative;
}
#p1c {
width:50px;
height:50px;
background-color:#55e;
margin-top:50px;
position:absolute;
top:30px;
}
#p2 {
width:200px;
height:150px;
background-color:#ea9;
position:relative;
}
#p2c {
width:50px;
height:50px;
background-color:#55e;
margin-top:50px;
position:absolute;
top:80px;
}


</style>
</head>
<body>

<div id='p1'>
<div id='p1c'></div>

</div>
<div id='p2'>
<div id='p2c'></div>



</div>




</body>
</html>

------解决方案--------------------
img2.position="absolute";

其他所有属性都加style,为啥这里你就不加呢?

img2.style.position="absolute";

竟然会这么大意的。