使用jQuery以百分比形式设置outerWidth 短版
如果不设置水平边距,我的代码运行良好。这就是为什么我的代码使用.width()来获取和设置元素宽度,但我不能对.outerWidth()执行相同的操作,因为它是只读的。有没有办法设置它 长版本 我有许多按钮(使用使用jQuery以百分比形式设置outerWidth 短版,jquery,css,css-float,Jquery,Css,Css Float,如果不设置水平边距,我的代码运行良好。这就是为什么我的代码使用.width()来获取和设置元素宽度,但我不能对.outerWidth()执行相同的操作,因为它是只读的。有没有办法设置它 长版本 我有许多按钮(使用float:left)具有不同的宽度,我希望每个按钮都有一个单独的宽度,以便创建一个漂亮且优化的按钮表 所以我写了这个: buttons = $('.button-table > button'); maxWidth = Math.max.apply( Math,
float:left
)具有不同的宽度,我希望每个按钮都有一个单独的宽度,以便创建一个漂亮且优化的按钮表
所以我写了这个:
buttons = $('.button-table > button');
maxWidth = Math.max.apply(
Math,
buttons.map(function(){
return $(this).width();
}).get()
);
columns = Math.floor($('#container').width()/maxWidth);
buttons.width(100/columns+'%');
这段代码可以工作,但是如果我为按钮设置水平边距,最后一个按钮会在下一行移动
注意:我更喜欢百分比,因为如果我使用此代码,我通常会在容器的右端看到一些像素(我可以使用不同的颜色看到它们):
注意
这是我关于堆栈溢出的第一个问题,如果我在使用这个平台时出错,请原谅。如果我理解正确的话。您想为这些按钮设置
宽度
+边距
我们开始吧
你可能已经知道了<代码>总宽度=边距
+边框
+填充
+内容宽度
所以,在你的情况下,你可以这样做
var buttons = $('.button-table > button'),
// filter out the widest element
widest = buttons.sort(function(a, b){ return $(a).outerWidth() - $(b).outerWidth(); }).pop(),
btn_width = Math.floor($('.button-table').width()/columns),
btn_margin = parseInt($(widest).css('margin-left')) + parseInt($(widest).css('margin-right'));
// set actual width
button.css({
width: btn_width - btn_margin
})
以下是解决方案:
无保证金:
有余量:
基本上,我在具有这种样式的按钮周围添加了div(使用class=“box”
):
.box {
float: left;
}
.box button {
margin-left: auto ;
margin-right: auto ;
margin-top: 5px;
margin-bottom: 5px;
display: block;
width: 90%;
white-space: nowrap;
}
这种CSS可能更好:它可以在不设置宽度的情况下拉伸按钮
jQuery代码是相同的(按钮变成.box
,.width()变成.outerWidth()…):
您将水平填充放在何处,例如#container
或button
?@Rezigned抱歉,我指的是边距,而不是填充(我刚刚解决了我的问题)。我用它来做按钮@MalSu-Sure:(我不知道为什么我的Firefox夜间版有时会在右边留下一些空间-如果有,就按F5)我很抱歉,伙计。我仍然无法理解你的问题。谢谢你试图帮助我:)@FrancescofRasinelli我已经用你的测试过了(用我的替换你的js部分,并在按钮上添加边距)。这对我来说很好。或者我误解了。好吧,问题是:在代码中没有列的定义,按钮没有使用整个容器的宽度(就像我的JSFIDLE一样——尝试移动垂直条)。
.box {
float: left;
}
.box button {
margin-left: auto ;
margin-right: auto ;
margin-top: 5px;
margin-bottom: 5px;
display: block;
width: 90%;
white-space: nowrap;
}
boxes = $('#container > .box');
maxWidth = Math.max.apply(
Math, boxes.map(function() {
return $(this).outerWidth();
}).get());
columns = Math.floor($('#container').width() / maxWidth);
boxes.width(100 / columns + '%');