Partial to full expand/collapse w/ jQuery
I'd like to write a function to allow to expand and collapse a div. It is not quite as straight forward though. If the div is more than 50px high I need to add an icon ("expand") to allow expanding it to a full height. And when it is fully expanded I need to change the style of the icon to ("collapse") and collapse it back to 50px. The icon needs to be position to the right bottom corner of the div.
I can have multiple such divs on a page.
Now, I can get a height of the div but how do I do it for each one on the page and onload?
var divHeight = $('.myDiv').height();
if (divHeight > 50) {
$('.icon_collase').appendTo('.myDiv');
}
<style>
.collasedDiv {
max-height:50px;
}
</style>
$(".icon_collase").click(function() {
$('.icon_collase').toggleClass('icon_collase icon_expand');
$('.myDiv').addClass('collasedDiv');
}
<div class="myDiv">
// content here
</div>
<div class="myDiv">
// another content here
</div>
I'm not sure anyone will write the entire code for you, but here is a set of accordion items I programmed with a "Show More" link for longer items. You may be able to use this as a 90% starting point and figure out the other 10%.
Link: "More Info" Style Accordion
To get all related divs, do this:
var $YourDivs = $('.myDiv').filter(function(){ return $(this).height() > 50; });
Then you need to append something to each of them like this:
// since we're passing in a set, jquery will clone '.icon-collase' for you
$('.icon_collase').appendTo($YourDivs);
Then add the class toggle function to all the collapse icons:
$(".icon_collase").click(function() {
$(this).closest('.myDiv').toggleClass('icon_collase icon_expand')
});
$(".icon_collase").click(function(e) {
$(e.target).toggleClass('icon_collase icon_expand');
$(e.target).closest('.myDiv').addClass('collasedDiv');
$(".myDiv").each(function(){
var divHeight = $(this).height();
if (divHeight > 50) {
$(this).append('icon_collase');// you might want to edit this icon_collase should be a html element ?
}
});
}
to get the element being clicked you assign event variable to the function click and get the element by calling e.target
closest() will select the first parent element that matches the selector '.myDiv'.
When performing the click you will loop through each .myDiv to find their height, so $(this) represents the div being interacted with.
精彩评论