5

任意の型の要素があります。最初の要素と同じ位置とサイズを持つ同じまたは異なるタイプの別の要素を作成したいと思います。要素は、配置されている場合と配置されていない場合があります。

たとえば、<select>幅/高さ auto など、その内容に応じて、特定のサイズの から始める場合があります。<div>同じ位置に同じサイズで表示される新しいものを作成したい。

要素のフロート、クリア、位置、幅、高さ、マージン、パディングをコピーしてみましたが、これは少し面倒です。また、Firefox では動作しますが、Webkit でテストすると、いくつかの奇妙な問題が発生します。それを理解するために多くの時間を費やす前に、私がやりたいことをすでに処理している jQuery または jQuery UI 機能があるかどうかを知りたいと思います。

この質問は既存の質問と似ていることは理解していますが、私の質問には、異なるタイプの要素を扱う必要があるという重要な違いがありclone、解決策としては除外されています。

4

3 に答える 3

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();
于 2010-10-06T18:53:45.330 に答える
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);
于 2010-10-06T18:29:04.947 に答える
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);
于 2012-02-10T11:42:15.463 に答える