5

我有一个任意类型的元素。我想创建另一个元素,类型相同或不同,其位置和大小与第一个元素相同。该元素可以定位也可以不定位。

例如,我可能从具有<select>特定大小的 a 开始,可能取决于其内容,即宽度/高度自动。我想创建一个<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

仅复制元素的偏移量并将其绝对定位在页面上怎么样?

假设您在页面某处有一个尺寸为 100x25 像素的输入元素。

<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 回答