【发布时间】:2018-07-23 00:56:51
【问题描述】:
我正在尝试在触发点击事件时选择父元素。我正在尝试以下。我有 5 个具有相同类和不同内容的侧边栏框,如下所示。
首先,侧边栏显示一些内容,当我们单击阅读更多按钮时,它显示父元素的其余内容。之后,阅读更多按钮隐藏在父框中并显示关闭按钮,但它显示所有其他框,而不是父框。
那么,如何选择我唯一的父级关闭按钮?请在下面查看我的 javascript 代码。
<div class="artist_bio sidebar-box">
<!-- Default Show this text -->
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. In, exercitationem.</p>
<!-- After Clcik on .read-more-button it's showes -->
<p>Lorem ipsum dolor sit amet.</p>
<p class="read-more"><a href="#" class="button moretag read-more-button">Read More</a></p>
<p class="read-less"><a href="#" class="button read-less-button">Close</a></p>
</div>
JavaScript 来了-
$(function() {
var $el, $ps, $up, totalHeight;
var $orgHeight = $('.sidebar-box').height();
$(".sidebar-box .read-more-button").click(function() {
totalHeight = 0
$el = $(this); $p = $el.parent(); $up = $p.parent();
$ps = $up.find("p:not('.read-more')");
$ps.each(function() {
totalHeight += $(this).outerHeight();
// FAIL totalHeight += $(this).css("margin-bottom");
});
$up
.css({
"height": $up.height(),
"max-height": 9999,
"opacity": 1,
})
.animate({
"height": totalHeight
},500,function(){
//Callback - after the animation is over
jQuery('#masonry-content').masonry(); });
// fade out read-more
$p.fadeOut();
$('.read-less-button').fadeIn(50);
// prevent jump-down
return false;
});
/*Another Code*/
$(".sidebar-box .read-less-button").click(function() {
$el = $(this);
$p = $el.parent();
$up = $p.parent();
totalHeight = $up.height();
$up
.css({
"height": totalHeight,
"max-height": 9999
})
.animate({
"height": $orgHeight
},500,function(){
//Callback - after the animation is over
jQuery('#masonry-content').masonry(); });
// fade out read-less
$p.fadeOut();
$('.read-more').fadeIn();
// prevent jump-down
return false;
});
});
【问题讨论】:
-
其实我不是javascript专家。我在学习。实际上不是。 @AluanHaddad
-
如果我没看错,您可以使用
.closest("parent_selector"),然后使用.find(close_button)。在您的情况下,它将是.closest(".sidebar-box") -
@Huangism 我认为它会起作用。请让我检查一下。
-
这样更好。请注意,
$是对jQuery的引用,您应该选择其中一个($或jQuery)并始终如一地使用它。另外,将"use strict";添加为程序的第一行。 -
@AluanHaddad 对不起,不是你。我
标签: javascript jquery html