jQuery动画实现显示更多

知识点

  1. 删选选择器gt(2)获取第三个之后的

  2. var text = $(this).text() === ‘显示更多’ ? ‘隐藏’ : ‘显示更多’;

    三目运算符赋值

  3. slideToggle()改变状态

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        *{
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .box{
            width: 450px;
            border: 1px solid #cccccc;
            margin: 100px auto;
            text-align: center;
        }

        .box ul{
            overflow: hidden;
        }

        .box ul>li{
            width: 150px;
            height: 30px;
            line-height: 30px;
            float:left;
        }

        .box button{
            width: 150px;
            height: 30px;
            line-height: 30px;
            border: 1px solid #cccccc;
            margin: 10px 0;
            outline: none;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="box">
        <ul>
            <li>香蕉</li>
            <li>苹果</li>
            <li>梨子</li>
            <li>猕猴桃</li>
            <li>橙子</li>
            <li>桃子</li>
            <li>哈密瓜</li>
            <li>西红柿</li>
            <li>西瓜</li>
            <li>荔枝</li>
            <li>榴莲</li>
            <li>人生果</li>
        </ul>
        <button>显示更多</button>
    </div>

<script type="text/javascript" src="lib/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $(function () {
        // 1. 隐藏标签
        $('.box>ul>li:gt(2)').hide();
        // 2. 监听按钮的点击
        $('.box>button').click(function () {
            // 2.1 处理按钮中的文字
            var text = $(this).text() === '显示更多' ? '隐藏' : '显示更多';
            $(this).text(text);
            // 2.2 动画
            $('.box>ul>li:gt(2)').slideToggle();
        });
    });
</script>
</body>
</html>

运行结果

在这里插入图片描述
在这里插入图片描述

发布了270 篇原创文章 · 获赞 123 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/KaiSarH/article/details/104574166
今日推荐