4

我正在尝试更改按钮的宽度以匹配 jquery 中其上方文本框的宽度。我试图通过使用以下行来完成此操作:

$("#myButton").css("width", $("#textbox").width());

在下面的代码中:

JSFiddle

查询:

$('#tabs').tabs();
$("#myButton").css("width", $("#textbox").width());

HTML:

<div id="tabs">
    <ul>
        <li><a href="#tabs-1"> Tab 1</a></li>
        <li><a href="#tabs-2" id="productTab">Tab 2</a></li>
    </ul>
    <div id="tabs-1" class="buttons" class="ui-widget">
    </div>
    <div id="tabs-2">
        <table>
            <tr>
                <td>
                    <input type="text" id="textbox" />
                </td>
            </tr>
            <tr>
                <td>
                    <button id="myButton">My Button
                    </button>
                </td>
            </tr>
        </table>
    </div> 
</div>

我相信,由于我使用的是制表符,因此文本框的宽度不会立即可用。

4

8 回答 8

4

在使用之前获取宽度.tabs

var width = $("#textbox").width();
$('#tabs').tabs();
$("#myButton").css("width", width);

演示:http: //jsfiddle.net/4EfAJ/12/

于 2013-06-27T12:53:49.673 回答
4

The problem is because the textbox is hidden (in the tab which is not being displayed) and therefore it's width cannot be calculated. The work around is to clone the element, append it, then get it's width and finally remove it from the DOM.

$('#tabs').tabs();
var $textboxClone = $('#textbox').clone().appendTo('#tabs');
$("#myButton").css("width", $textboxClone.width());
$textboxClone.remove();

Updated fiddle

Note; the minor difference in widths here is due to padding and/or margin differences which I'll let you solve in CSS.

于 2013-06-27T12:53:14.630 回答
2

单击包含表单的选项卡后,您可以设置宽度。见这里:http: //jsfiddle.net/4EfAJ/16/

$('#tabs').tabs();
$("#productTab").on("click",function() {
    $("#myButton").css("width", $("#textbox").width());
});
于 2013-06-27T12:58:23.830 回答
0

先试试这个:

<input type="text" id="textbox" **style="width:300px"** />

然后

$("#myButton").css({width:$("#textbox").width()+"px"});

希望它会导致一些解决方案

于 2013-06-27T12:55:25.380 回答
0

Try changing the width of the button once its tab is visible, not before:

 $('#tabs').tabs({
  activate: function(event, ui){
    if (ui.newTab.index() == 1){
        $("#myButton").css("width", $("#textbox").width() );
    }
  }
});
于 2013-06-27T12:52:25.933 回答
0

The $("#textbox") is invisible at the time page loaded, so you can't retrieve it's width. Try to put these stuff on the first tab. or resize the width when the second is active

于 2013-06-27T12:53:25.020 回答
0

更灵活,只需将宽度分配给按钮。无论他是否可见,都不会生气。

#textbox {
  width: 250px
}

如果您可以通过 css 解决问题,请在启动 javascript 之前始终选择这种方式。

于 2013-06-27T13:06:29.553 回答
0

我认为这应该有效

$("#myButton").css("width", $("#textbox").css("width"));
于 2013-06-27T12:51:39.840 回答