如何使用javascript在div上设置相等宽度
我有五行,看起来像这样: 这是一个ul和lis。我希望第一个li“text”在所有行上都相等。为此,我需要寻找最宽的li,然后将新的with应用于所有li (ul>li>span&ul) Text>Li 1 | Li 2 | Li 3如何使用javascript在div上设置相等宽度,javascript,jquery,width,equals,Javascript,Jquery,Width,Equals,我有五行,看起来像这样: 这是一个ul和lis。我希望第一个li“text”在所有行上都相等。为此,我需要寻找最宽的li,然后将新的with应用于所有li (ul>li>span&ul) Text>Li 1 | Li 2 | Li 3 Textlong>Li 1|Li 2|Li 3 Short>li1 | li2 | li3 Longer13456>Li 1 | Li 2 | Li 3 我使用了以下函数来设置等高。稍微修改一下。但这没有任何意义 function equalWidth() {
Textlong>Li 1|Li 2|Li 3
Short>li1 | li2 | li3
Longer13456>Li 1 | Li 2 | Li 3 我使用了以下函数来设置等高。稍微修改一下。但这没有任何意义
function equalWidth() {
var span = $('#tableLookAlike li.tr > span'),
tallest = 0,
thisHeight = 0;
setEqWidth = function(elem) {
elem.each(function() {
widest = 0;
thisWidth = $(this).outerWidth();
console.log(tallest, thisWidth)
// if I remove this it gives me the right width
elem.each(function() {Width)
if (thisWidth > widest) {
widest = thisWidth;
elem.css({'width': widest});
}
});
});
}
setEqWidth(span);
}
当我删除第二个元素时,日志显示为92、69、68、118,当我将其放回原处时,日志显示为92、130、168、206。
有人知道这里发生了什么吗
Aynway,我如何解决这个问题?您需要在循环结束时设置元素的宽度。否则,最宽的值只是临时的最高值
setEqWidth = function(elem) {
elem.each(function() {
widest = 0;
thisWidth = $(this).outerWidth();
console.log(tallest, thisWidth)
elem.each(function() {
if (thisWidth > widest) {
widest = thisWidth;
}
});
});
elem.css({'width': widest});
}
如果我要这么做,事情会是这样的:
var greatestWidth = 0; // Stores the greatest width
$(selector).each(function() { // Select the elements you're comparing
var theWidth = $(this).width(); // Grab the current width
if( theWidth > greatestWidth) { // If theWidth > the greatestWidth so far,
greatestWidth = theWidth; // set greatestWidth to theWidth
}
});
$(selector).width(greatestWidth); // Update the elements you were comparing
请记住:明确设置宽度不会考虑相关元素上的任何
填充
,因此如果这些元素设置了左填充
或右填充
,由于填充被合并到CSS框模型的宽度中,因此最终的宽度将大于原始的最大宽度
这甚至会使您的原始元素比开始时更宽。这同样适用于使用填充顶部
和填充底部
设置高度
如果你想达到超精确,你需要考虑像下面这样的代码(如果你没有使用percanties或ems或像素分数来设置填充,你可以使用parseInt()
而不是parseFloat()
):
简洁一点
var widest = 0;
$("#tableLookAlike li.tr > span").each(function () { widest = Math.max(widest, $(this).outerWidth()); }).width(widest);
谢谢你,我是这样解决的,但是没有必要每次都去元素两次。我有一段时间没有使用jQuery了,谢谢你的更正。我需要的是更改$(this).width()
到>$(this).outerWidth()
以考虑填充和边框。谢谢你。
var maxWidth = 0;
var $els = $('.your-selector');
$els.each(function(){
var w = $(this).width();
if(w > maxWidth){
maxWidth = w;
}
}
$els.each(function(){
var $el = $(this);
var padding = parseFloat($el.css('padding-left'),100) + parseFloat($el.css('padding-right'),100);
$el.width(maxWidth - padding);
});
var widest = 0;
$("#tableLookAlike li.tr > span").each(function () { widest = Math.max(widest, $(this).outerWidth()); }).width(widest);