2010-10-06 65 views
5

我有一个任意类型的元素。我想要创建另一个元素,或者是与第一个元素具有相同位置和大小的相同或不同类型的元素。该元素可能定位或不定位。jQuery可以将元素的边界(位置,大小,边距等)复制到另一个元素吗?

例如,我可能从具有一定尺寸的<select>开始,可能取决于其内容,即宽度/高度自动。我想创建一个新的<div>,它出现在相同的位置并具有相同的大小。

我试着复制元素的浮点,清除,位置,宽度,高度,边距和填充,但这有点麻烦。另外,虽然它在Firefox中起作用,但在Webkit上测试时遇到了一些奇怪的问题。在我花更多时间搞清楚之前,我想知道是否有一些jQuery或jQuery UI功能已经处理了我想要做的事情。

我意识到这个问题类似于an existing one,但我的重要区别是需要与不同类型的元素一起工作,这排除clone作为解决方案。

回答

4

这是不高效,测试或完成。它可能类似于你已经在做的事情。但我想我会发布它:

var positioningProps = ["float","position","width","height","left","top","marginLeft","marginTop","paddingLeft","paddingTop"]; 
var select = $("#mySelect"); 
var div = $("<div>").hide().before(select); 
// don't do this kind of loop in production code 
// http://www.vervestudios.co/jsbench/ 
for(var i in positioningProps){ 
    div.css(positioningProps[i], select.css(positioningProps[i])||""); 
} 
select.hide(); 
3

如何复制元素的偏移量并将其绝对定位在页面上?

假设您在尺寸为100x25px的页面上有某个输入元素。

<input type="text" id="firstname" style="width: 100px; height: 20px" /> 

而你想在其上放置一个div(并隐藏输入)。

// Store the input in a variable 
var $firstname = $("#firstname"); 

// Create a new div and assign the width/height/top/left properties of the input 
var $newdiv = $("<div />").css({ 
    'width': $firstname.width(), 
    'height': $firstname.height(), 
    'position': 'absolute', 
    'top': $firstname.offset().top, 
    'left': $firstname.offset().left 
}); 

// Add the div to the body 
$(body).append($newdiv); 
+0

这种方法具有流体布局的问题。如果在“#firstName”之前插入一个元素,将firstName向下移动,则“newdiv”页面将不能正确排列。 – 2010-10-06 18:55:59

+0

这可能是真实的,在液体布局情况下需要不同的解决方案。 – Marko 2010-10-06 19:01:37

1

你可以找到一个元素的界限使用这个插件到jQuery。这将只是一个简单的事情,设置你感兴趣的其他对象的任何属性。

http://code.google.com/p/jquery-ui/source/browse/branches/labs/powella/coverslide/res/js/jquery/jquery.bounds.js?r=2698

/* 
* jQuery.bounds 
* author: Andrew Powell 
*/ 

(function($){ 

     $.fn['bounds'] = function() 
     { 
       var t = this, e = t[0]; 
       if (!e) return; 

       var offset = t.offset(), pos = { width:e.offsetWidth, height:e.offsetHeight, left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0 }; 

       pos.left = offset.left; 
       pos.top = offset.top; 

       //right and bottom 
       pos.right = (pos.left + pos.width); 
       pos.bottom = (pos.top + pos.height); 
       pos.x = pos.left; 
       pos.y = pos.top; 
       pos.inner = {width: t.width(), height: t.height()}; 

       $.extend(pos, {toString: function(){ var t = this; return 'x: ' + t.x + ' y: ' + t.y + ' width: ' + t.width + ' height: ' + t.height + ' right: ' + t.right + ' bottom: ' + t.bottom; }}); 

       return pos; 
     }; 

})(jQuery); 
+0

如果设置了左/上边距或左/上边距,则不起作用。 pos.left不再偏移。有界的矩形将被边界/边界/填充量向右移动。 – chubbsondubs 2012-02-29 18:42:04

相关问题