【问题标题】:Click and show more element单击并显示更多元素
【发布时间】:2016-08-09 13:08:48
【问题描述】:

我想在您点击 div ShowMore 时显示更多内容,但是当我这样做时,所有部分都会显示更多内容,而不是我刚刚单击的元素。

总而言之,当您单击 div .showMore 时,div .panel 会增加高度以显示隐藏文本。但是,当我点击 .showMore 时,每个带有 .panel 类的 div 也会进行动画处理,而我只是被点击的 div 动画高度

我想这是我想念的一小行代码

JS

$(".showMore").click(function (){
if ($(".panel").height() == 100) {
    $(this).css({transform:"rotate(90deg)"});
$(".panel").animate({height: "250px"});
}
else if ($(".panel").height() == 250) {
    $(this).css({transform:"rotate(0deg)"});
    $(".panel").animate({height: "100px"});
}
});

Full code here: Codepen

【问题讨论】:

  • 您应该使用 ID 来确定要展开哪个面板
  • 我不能使用类?
  • 如果你正在使用一个类,你的类的每一次出现都会被扩展。如果您使用特定 ID,则只会展开此 ID

标签: javascript jquery


【解决方案1】:

查找包含被点击元素的类panel的元素:

$(".showMore").click(function (){

  var panel = $(this).closest(".panel");

  if (panel.height() == 100) {
    $(this).css({transform:"rotate(90deg)"});
    panel.animate({height: "250px"});
  }
  else if (panel.height() == 250) {
    $(this).css({transform:"rotate(0deg)"});
    panel.animate({height: "100px"});
  }
});

注意:去掉 html 中重复的 ids。

【讨论】:

  • 当你写“panel.animate”时,js就知道我们在谈论“.panel”这个类了吗?
  • @Pierreszwk - 上面代码中的变量panel 是一个jQuery 对象,它用panel 类包装了DOM 元素。
【解决方案2】:

你只需要通过访问它的父元素来更多地使用$(this)

    //alert('ok');
    $(".showMore").click(function (){
    if ($(".panel").height() == 100) {
        $(this).css({transform:"rotate(90deg)"});
    $(this).parent(".panel").animate({height: "250px"});
    }
    else if ($(this > ".panel").height() == 250) {
        $(this).css({transform:"rotate(0deg)"});
        $(this).parent(".panel").animate({height: "100px"});
    }

【讨论】:

  • 我只是在阅读 jQuery 上的 '.parent()' 方法!非常感谢;)
  • 没问题。如果您认为这回答了您的问题,请将其标记为已接受的答案。 :)
【解决方案3】:
$(".showMore").click(function (){
    var height=$(this).parent().height();
    if (height == 100) {
        $(this).css({transform:"rotate(90deg)"});
    $(this).parent().animate({height: "250px"});
    }
    else if (height == 250) {
        $(this).css({transform:"rotate(0deg)"});
        $(this).parent().animate({height: "100px"});
    } 
});

http://codepen.io/beshoysemsem/pen/xOQmRQ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多