div中的CSS绝对定位元素
我有一个.toy
div
里面有一些.toy
div
。 我想把toy
放在wall
。 float:left
property很适合我。
现在问题是我想添加position:absolute
toy
div的position:absolute
,以便以后可以拖动它。 我怎么能通过Javascript或CSS来做到这一点?
应用position:absolute
,所有toy
都会到达wall
左上角并相互隐藏。
wall
的宽度和高度是恒定的,但toy
的宽度和高度是可变的, toy
div的数量也是动态的,并且数量增加toy
需要排列成行 。
任何建议都会有所帮助,请注意我无法避免使用position:absolute
for dragging。
body{ text-align:center; } .clearfix{ clear:both; } .wall { border: 5px solid #cde; margin:auto; width:200px; padding:10px; } .toy{ background-color: #BBCCEE; border:1px solid #8899BB; margin:5px; width: auto; padding:5px; float:left; } .tall{ padding-top:10px; } $(document).ready(function() { $('.toy').each(function(index) { var position = $(this).offset(); var prevPosition = $(this).prev().offset(); $(this).css({ //top: position.top, //left:position.left, //position:'absolute', }); }); }); T1 T2 T3333333 T4 T5 T6 T7 T8
这是JSBin的代码 。
我正在建立一个完全正确的网站(抱歉非英语的东西):
http://moveit.canassa.com/cartao/4/
链接现在已经破了,但这里有一个jsFiddle,显示我在说什么:
http://jsfiddle.net/canassa/Z9N3L/
“玩具”div使用绝对位置:
.toy{ width: 100px; height: 25px; position: absolute; z-index: 0; }
绝对位置的问题是玩具将相对于页面而不是“墙”容器,以便修复您必须使墙容器相对:
#wall{ position: relative; overflow: hidden; }
溢出:隐藏也是我发现的一个很好的技巧。 它使可拖动的对象位于墙上容器的“下方”。
使用jQuery使其可拖动没有什么大秘密:
// Creates a toy div inside the wall $(MV.wallId).append(''); box = this.getBox(); // return the "toy" that I've just created. $('#' + this.getId()).draggable(); // make it draggable
加
position:relative
到墙div
如果你刚刚使用了jQueryUI .draggable()
这将会容易得多。 它不需要定位元素。
如果您已经开始使用此插件,那么您就有了正确的想法。 让元素流入到位,然后计算它们的位置和设置position: absolute
以及left
和top
在运行时的结果。
将.wall
设置为position: relative
。 然后:
var tPos; $('.toy').each(function(index) { tPos = $(this).position(); $(this).css({ left: tPos.left, top: tPos.top }); }; $('.toy').css({ position: absolute });
当玩具绝对定位时, .toy
的高度和每个.toy
的宽度.toy
崩溃,但你可以在上面的.each
循环中添加更多的线来获取/设置它们的宽度和高度。
如果可以动态添加新玩具而不按照您的建议重新加载页面,这显然不起作用。 要处理它你可以将它们切换回position: relative
,添加新的,在流程中获取新的位置,然后设置位置并切换回position: absolute
。 任何被拖出的元素都会在流程中出现空白,但我看不到任何简单的方法。
绝对应该定位的元素,必须具有样式位置:相对。 (必须是目标元素的父级)
每个.toy
的容器div
必须具有position:relative
set。 这样,其子元素的位置0变为其左上角。 像这样:
Blah. Blah.
和:
.parent { position: relative; } .child { position: absolute; left: 10px; /* This is 10 pixels from the parents left side */ top: 10px; /* This is 10 pixels from the parents top side */ }
祝好运。