我尝试在一个循环中测量页面上的一个元素,然后从一个包含元素的宽度中减去它。但是,当我使用.width()时,它返回的值与我检查元素时得到的值不同。我也尝试过inner和outer width。即使这样,它看起来也不能准确地获得宽度,因为我所做的是以跨度中文本的宽度为例,第一个文本被包装在一个名为smoked pit wings的跨度中,我们计算这个宽度,从h5的总宽度中减去它,我们应该得到dotted元素的宽度,你可以看到下面的图像演示了这一点,但是点和数字应该在右边对齐,但是它们不是。
任何帮助都是最好的
到目前为止,以下是我的代码
var colWidth = $(".food-menu__column").width();
var array = [];
$('.food-menu__item').each(function(i, obj) {
var width = $(obj).width();
array.push(width);
});
console.log(colWidth);
console.log(array);
$('.dotted').each(function(i, obj) {
var widthDotted = colWidth - array[i];
$(obj).width(widthDotted);
console.log(widthDotted);
});下面是代码布局的图像,虚线跨度元素需要是容器列的宽度减去左侧文本的宽度,然后左边的价格和点应该匹配,但它们略有偏离,但我不明白为什么,因为jquery至少应该测量它们相同的宽度。

下面是生成的html的图像。

发布于 2018-08-28 00:43:32
我会在flexbox中使用CSS,不用担心宽度的计算和设置。使用CSS也可以通过其他方式来完成,但这似乎是更简单的解决方案。
.container {
display: flex;
}
.column.left, .column.right {
width: auto;
flex: 0 0 auto;
margin-top: 5px;
padding-right: 4px;
padding-left: 4px;
}
.column.center {
flex: 1;
text-align: center;
border-bottom: 2px dotted black;
margin-bottom: 10px;
}<div class="container">
<div class="column left">Pizza Pie</div>
<div class="column center"> </div>
<div class="column right">$11.99</div>
</div>
<div class="container">
<div class="column left">Ice</div>
<div class="column center"> </div>
<div class="column right">$0.99</div>
</div>
发布于 2018-08-28 00:24:50
元素的默认布局是CSS Box Model。在该模型中,为width或height返回的默认大小没有考虑填充、边框或边距。这在一开始总是令人困惑,这也是为什么你会发现,即使你设置了一个元素的大小,它最终呈现的结果往往比这个值稍大一些。
然而,offsetWidth的DOM做到了。
发布于 2018-08-28 00:29:42
嗯,这并不是开箱即用的完美解决方案,但您可能想要尝试一下这个解决方案。
p {
background:inherit;
width: 70%;
max-width: 40rem;
min-width: 300px;
margin: 0 auto;
position:relative;
}
p:before {
content: '';
position: absolute;
bottom: .2rem;
width: 100%;
height: 0;
line-height: 0;
border-bottom: 2px dotted #ddd;
}
.desc {
background: inherit;
display: inline;
z-index: 1;
}
.price {
position: absolute;
min-width: 4rem;
bottom: 0;
right: 0;
padding-left: .2rem;
text-align: right;
z-index: 2;
}
.price:after {
content: '$';
}<p>
<span class='desc'>Some item</span>
<span class='price'>Price</span>
</p>
<p>
<span class='desc'>Some item - 2</span>
<span class='price'>Price -2</span>
</p>
https://stackoverflow.com/questions/52043336
复制相似问题