按钮实现文字的收缩与展开

570 阅读1分钟

//首先要在上方定义一个盒子,放上文字

<script src='https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js'></script>
<script>
    let pd = true              //定义一个为true的值
    let str = $('.box p').html()          //获取盒子里面的文字
    $(".a1").click(function (e) {         //点击的时候执行的操作
        e.preventDefault();               //在这里可以暂时忽略 意思是阻止默认时间进行
        if (pd) {                        //判断 pd是否为true
            $('.box p').html(str.slice(0, 100))  //截取字符串 
            $('.a1').html('&gt;&gt;展开')    //按钮切换成展开
        } else {                     //相反的操作 点击展开时进行的操作
            $('.box p').html(str)       //把全部的字符串插入进盒子
            $('.a1').html('&gt;&gt;收缩')   //显示收缩按钮
        }
        pd =! pd         //无论执行完上面 哪一个判断  都要给pd取反
        console.log(pd);
    });

</script>