2010-10-06 61 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

相關問題