我想设置包装器的宽度,这样使用jQuery时段落不会比图像宽。我犯了什么错误?
$(function(){
$('.wrapper').css({
width: $(this).children('img').width(),
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<img src="http://www.placecage.com/400/200"/>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. </p>
</div>
<div class="wrapper">
<img src="http://www.placecage.com/500/500"/>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. </p>
</div>
<div class="wrapper">
<img src="http://www.placecage.com/300/300"/>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. </p>
</div>
代码中的问题是同时更新所有.wrapper
元素,而且css()
方法中的this
将引用document
,而不是.wrapper
元素。
还有一个额外的问题,即图像可能还没有加载,因此在那之前它们将具有0
的宽度。
要执行所需操作,请将load
事件处理程序挂接到img
元素,并从中设置同级p
元素的宽度:
$(function() {
$('.wrapper img').on('load', function() {
$(this).next('p').width($(this).width());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<img src="http://www.placecage.com/400/200" />
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. </p>
</div>
<div class="wrapper">
<img src="http://www.placecage.com/500/500" />
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. </p>
</div>
<div class="wrapper">
<img src="http://www.placecage.com/300/300" />
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s. </p>
</div>