jQueryは、要素の境界(位置、サイズ、マージンなど)を別の要素にコピーできますか?
-
28-09-2019 - |
質問
任意のタイプの要素があります。最初と同じ位置とサイズを持つ同じタイプまたは異なるタイプの別の要素を作成したいと思います。要素が配置されている場合とない場合があります。
たとえば、aから始めるかもしれません <select>
おそらくその内容、すなわち幅/高さの自動に依存する特定のサイズで。新しいものを作りたいです <div>
同じ位置に表示され、同じサイズがあります。
要素のフロート、クリア、位置、幅、高さ、マージン、パディングをコピーしてみましたが、これは少し面倒です。また、Firefoxで動作しますが、WebKitでテストするときにいくつかの奇妙な問題に遭遇しています。それを把握するのにもっと時間を費やす前に、私がやりたいことをすでに世話しているjQueryまたはjQuery UIの機能があるかどうかを知りたいです。
私はこの質問が似ていることを理解しています 既存のもの, 、しかし、私のものには、異なるタイプの要素を使用する必要があるという重要な区別があります。 clone
解決策として。
解決
これは効率的でも、テストされていない、または完全ではありません。そして、それはおそらくあなたがすでにしていることに似ています。しかし、とにかく投稿すると思いました:
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();
他のヒント
要素のオフセットをコピーして、ページに絶対に配置するだけではどうですか?
ページのどこかに入力要素があり、寸法が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);
このプラグインをjQueryに使用して、要素の境界を見つけることができます。これは、他のオブジェクトに興味のあるプロパティを設定するという単純な問題です。
/*
* 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);