将对象的位置设置为内联样式到自身?

时间:2013-05-16 06:05:22

标签: jquery css css-position

我正在尝试构建一个包含8个div的响应式设计。我需要这些div具有内部CSS样式的绝对定位,左侧和顶部位置。为了保持响应,我无法用CSS定位它们。

我想等到div加载然后使用jQuery来获取这些div的位置,然后将这些信息传回各自的内联样式。

如果我使用文件就绪,它适用于左:0,右:0到我的所有div。如果我使用文档加载它根本不会激活代码。

$(document).ready(function(){
  $("div.item").each(function(i, obj) {
    var posfix = $(this).position();
    var getW = $(this).width();
    var getH = $(this).height();
    $(this).children().text( "left: " + posfix.left + ", top: " + posfix.top );//test
    $(this).children().append( "height: " + getH + ", width: " + getW );//test
    $(this).css({position: 'absolute',left:posfix.left,top:posfix.top,width:getW,height:getH});//set
   });
});     

此处测试代码jsFiddle

1 个答案:

答案 0 :(得分:0)

试试这个:

$(window).load(function()
{
  //your code here
});

没有文件加载这样的东西。 :)

您也可以尝试使用offset()返回相对于文档的位置(postion()返回相对于的位置。

有关详细信息,请查看此问题 - offset