如何构建一个jQuery驱动的切换器来添加/删除css属性

How to build a jQuery-powered switcher to add/remove css attributes?

本文关键字:切换器 添加 css 删除 属性 jQuery 构建 何构建 一个      更新时间:2023-09-26

我正在尝试构建一个盒子容器,当单击"阅读更多"按钮时会展开,并在单击同一按钮时折叠到初始大小(现在是"折叠"按钮)。

在 DOM 中,我在.post容器内有一个.leer-mas按钮。以及以下 jQuery 代码:

//When link with class .leer-mas is clicked, get the parent element's id and add some css attributes
$('.leer-mas').click(function() {
    var item = $(this).closest('.post');
    item.css('height', 'auto');
    $(this).addClass('leer-menos');
    $(this).text('Leer menos');         
});

//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$('.leer-mas.leer-menos').click(function() {
    var item = $(this).closest('.post');
    item.removeAttr('height');
    $(this).removeClass('leer-menos');
})

第一个动作就像一个魅力。但是第二个动作什么也没做...而且我认为我缺少jQuery的一些基础知识,因为语法是相同的,也许这不是它应该:)的方式

有什么想法吗?谢谢。

编辑 - 我的代码上有一些错误。虽然我仍在尝试使用单个切换台来获取它,但我有一个工作版本。

新的 DOM 看起来像这样:

<div class="post">
    <div class="leer mas">
    </div>
    <div class="leer menos">
    </div>
</div>

代码现在如下所示:

//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.mas').click(function() {
    var item = $(this).closest('.post');
    //Send the id to the PHP script, which returns 1 if successful and 0 if not
    item.css('height', 'auto');
    $(this).hide();
    $(this).next('.leer.menos').show();
});

//When link with class .leer-mas is clicked, get the parent element's id (which is also that element's id in the database)
$('.leer.menos').click(function() {
    var item = $(this).closest('.post');
    //Send the id to the PHP script, which returns 1 if successful and 0 if not
    item.removeAttr('style');
    $(this).hide();
    $(this).prev('.leer.mas').show();
});

这很顺利。但是,如果我让它与原始问题的预期结构一起工作(只有一个按钮),我会更高兴:)

这是因为类leer-menos是动态添加的...因此,当执行事件注册代码时,没有类 leer-masleer-menos 的元素。

一种可能的解决方案是使用事件委派

//When link with class .leer-mas is clicked, get the parent element's id and remove some css attributes
$(document).on('click', '.leer-mas.leer-menos', function() {
    var item = $(this).closest('.post');
    item.removeAttr('height');
    $(this).removeClass('leer-menos');
})

您正在尝试使用.removeAttr()来删除属性"样式"中的CSS属性。这是不正确的,请尝试使用item.removeAttr('style');

不完全是你要求的,但你可以从中得出想法:

$('.leer-mas').click(function() {
    var item = $(this).closest('.post');
    // toggle "height" between 'auto' and null
    item.css('height', item.css('height') == 'auto' ? null : 'auto' );
    // toggle class 'leer-menos'
    $(this).toggleClass('leer-menos');
    // toggle text between 'Leer menos' and ''
    $(this).text( $(this).is('.leer-menos') ? 'Leer menos' : '' );         
});