在这种情况下,我需要能够根据"p“元素的高度来设置"li”和"div“元素的高度。
例如,在以下HTML中:
<ul>
<li class ="activity-item">
<div class ="activity-detail">
<div class ="activity-comments">
<p class="activity-comments"></p>
</div>
</div>
</li>
<li class ="activity-item">
<div class ="activity-detail">
<div class ="activity-comments">
<p class="activity-comments">sample content - dummy text</p>
</div>
</div>
</li>
</ul>我需要将"div class=活动-细节“元素和"li class=activity”元素的高度设置为"p class=活动-注释“的高度。"p“元素可以是空的,即没有任何内容,也可以包含大量文本。
挑战是,如果"p“元素不是空的,那么首先能够获得所有"li”元素中所有"p“元素的高度,然后使用高度值来设置每个"li”元素的高度。
到目前为止,我有以下jquery,它可以获得"p“元素的高度(根据它们的内容),但不太确定如何使用检索到的高度值来设置"li”元素的高度:
$(document).ready(function(){
$('.activity-item p').each(function(index, element){
var commentsHeight = $(this).height();
alert(commentsHeight);
//the below does not quite work correctly yet
$('li.activity-item').css("height",commentsHeight);
$('div.activity-detail').css("height",commentsHeight);
});
});任何帮助/帮助都是非常感谢的。谢谢
发布于 2016-06-07 17:36:11
不确定我是否理解正确,但我得到每个p的高度(如果包含一些文本),并将该高度分配给最近的li元素和最近的div (类.activity-detail )
$(document).ready(function() {
$('.activity-item p').each(function(index, element) {
var txt = $.trim($(this).text());
var commentsHeight = 0;
if (txt !== "") {
commentsHeight = $(this).height();
}
if (commentsHeight > 0) {
$(this).parents('li').css('height', commentsHeight);
$(this).closest('div.activity-detail').css("height", commentsHeight);
}
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="activity-item">
<div class="activity-detail">
<div class="activity-comments">
<p class="activity-comments"></p>
</div>
</div>
</li>
<li class="activity-item">
<div class="activity-detail">
<div class="activity-comments">
<p class="activity-comments">sample content - dummy text</p>
</div>
</div>
</li>
</ul>
发布于 2016-06-07 17:28:11
使用Jquery,您可以使用parents()搜索每个p的li包装器。
$(document).ready(function(){
$('.activity-item p').each(function(index, element){
var commentsHeight = $(this).height();
alert(commentsHeight);
//Refer to "this" element and search for the parents
$(this).parents('li, div.activity-detail').css("height",commentsHeight);
});
});发布于 2016-06-07 17:30:29
如果您想要一个方便的工具通过备用资源做同样的事情:http://smohadjer.github.io/sameHeight/demo/demo.html
如果您想查看github:https://github.com/smohadjer/sameHeight中的代码
通过这个jQuery调用:
$('.parent-element').sameHeight({
//this option by default is false so elements on the same row can have
//different height. If set to true all elements will have the same height
//regardless of whether they are on the same row or not.
oneHeightForAll: true,
//this option by default is false. If set to true css height will be
//used instead of min-height to change height of elements.
useCSSHeight: true,
//this function will be called every time height is adjusted
callback: function() {
//do something here...
}
});或者没有所有选项:$('.parent-element').sameHeight();
https://stackoverflow.com/questions/37685568
复制相似问题