JQuery - 如何切换扩展/收缩宽度

JQuery - How to toggle expanding/shrinking width?

本文关键字:扩展 何切换 JQuery      更新时间:2023-09-26

到目前为止,我有一个单击函数可以扩展宽度,但不确定如何将其缩小回原始宽度。收缩后,.button应再次读取"显示详细信息"。

小提琴链接:https://jsfiddle.net/fpw9apmc/

$('.button').click(function() {
        $(".button").text("Hide Details");
        $(".expand").animate({
        width: "60%"
        }, {
            duration: 200,
            specialEasing: {
                width: 'linear'
            }
        });
    });

这是针对您的问题和工作 Jsfiddle 的编辑代码 -

$('.button').click(function() {
            var btnText =  $(this).text();
            if(btnText === "Hide Details"){
            $(this).text("Show Details");
            $(".expand").animate({
            width: 0
            }, {
                duration: 200,
                specialEasing: {
                    width: 'linear'
                }
            });
            }else{
                $(this).text("Hide Details");
            $(".expand").animate({
            width: "60%"
            }, {
                duration: 200,
                specialEasing: {
                    width: 'linear'
                }
            });
            }
        });

下面的脚本将为您提供帮助。

var clicked = false;
var previoswidth = 0;
$('.button').click(function () {
    $(".button").text("Hide Details");
    clicked = !clicked;
    if (clicked) {
        previoswidth = $(".expand").width();
        $(".expand").animate({
            width: "60%"
        }, {
            duration: 200,
            specialEasing: {
                width: 'linear'
            }
        });
    }
    else {
        $(".expand").animate({
            width: previoswidth
        }, {
            duration: 200,
            specialEasing: {
                width: 'linear'
            }
        });
    }
});

在这里小提琴

将切换功能分别应用于文本和宽度。这应该可以解决问题

var width = $(".expand").width();
$('.button').click(function() {
  $(this).text(function(i, text) {
    return text === "Show Details" ? "Hide Details" : "Show Details";
  })
  var toggleWidth = $(".expand").width() == 0 ? "60%" : "0";
  $(".expand").animate({
    width: toggleWidth
  }, {
    duration: 200,
    specialEasing: {
      width: 'linear'
    }
  });
});

你可以用CSS转换来做到这一点,并使用jQuery切换一个类。

用这个更新了你的小提琴:https://jsfiddle.net/oykwmj9c/2/

j查询:

$('.button').click(function() {
    if ($(".button").text() == "Show Details") {
    $(".button").text("Hide Details");
  } else {
    $(".button").text("Show Details");
  }  
  $(".expand").toggleClass("expanded");
});

.CSS:

.expand {
  background-color: red;
  width: 0;
  transition: width 1s ease-in-out;
}
.expanded {
  width: 60%
}
.button {
  color: #000;
  font-size: 2em;
}

.HTML:

<div class="expand">
  <a class="button" href="#">Show Details</a>
</div>