我有一个包含图像的 div,我希望它的高度为 440 像素,并带有一个“显示更多”按钮,使其达到全高 (2750 像素)。当处于全高状态时,我希望显示更多按钮显示为“显示更少”,并且当我单击它时功能会反转。
这是我的代码:
$('#photo_container').css('height','440px');
$('#photo_container').css('overflow','hidden');
$('.show_more').click(function(){
$('#photo_container').animate({'height':'2750px'},500);
$('.show_more').html('<h4>Show Less</h4>');
$('.show_more').addClass('show_less');
$('.show_more').removeClass('show_more');
});
$('.show_less').click(function(){
$('#photo_container').animate({'height':'440px'},500);
$('.show_less').html('<h4>Show More</h4>');
$('.show_less').addClass('show_more');
$('.show_less').removeClass('show_less');
});
和我的 HTML:
<div id="photo_container">
PHOTOS HERE...
</div>
<div class="show_more"><h4>Show more</h4></div>
我的代码允许我扩展,但它不会以相反的方式工作 (show less)。谁能给我解释一下这是为什么
最佳答案
改为将您的事件更新为:
$(document).on('click', '.show-less', function() {
$(document).on('click', '.show-more', function() {
因为您正在更改类,所以您需要绑定(bind)到类而不是元素。
关于jQuery 在 div 中显示更多/显示更少切换高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688383/