使用 jQuery.animate 实现简单的页面切换效果
涉及知识点
- jQuery.animate
- CSS position
css flex 布局
设计与实现
jQuery.animate()
语法:
$(selector).animate(styless[, duration][, easing][, callback]);
styles Object 必须 定义动画的 css 属性例如: { marginTop: 100px } ( css 属性需采用驼峰标记法书写 )
duration int 可选 定义效果完成的时长单位毫秒, 默认为 400 ms
easing: string 动画的运行曲线默认 swing (开始和结束缓慢中间加速)
callback Function 动画完成之后的回调函数
css 绝对定位
position: absolute; 绝对定位让 .page 都层叠在一起
然后通过修改 z-index 确定哪一个页面位于最上层
css flex 布局
非常方便的实现页面元素的定位
推荐一个学习 flex 布局的游戏 - Flexbox Froggy
最终实现
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>animate</title>
- <style>
- /* 页面样式 */
- * {
- margin: 0;
- padding: 0
- }
- html, body {
- height: 100%;
- width: 100%;
- overflow: hidden;
- }
- .page {
- position: absolute;
- height: 100%;
- width: 100%;
- display: flex;
- justify-content: center;
- align-items: center;
- z-index: 1;
- }
- .page.active {
- z-index: 2;
- }
- .page-blue {
- background-color: blue;
- }
- .page-red {
- background-color: red;
- }
- .page-slide {
- position: absolute;
- z-index: 999;
- width: 24px;
- height: 100%;
- right: 24px;
- display: flex;
- flex-direction: column;
- justify-content: center;
- text-align: center;
- }
- .slide-item {
- width: 24px;
- height: 24px;
- border-radius: 12px;
- background-color: #fff;
- cursor: pointer;
- }
- .slide-item:hover {
- border: 1px solid #222;
- }
- .slide-item:not(:last-child) {
- margin-bottom: 6px;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <!-- 页面 -->
- <div class="page page-blue active" id="page1">1</div>
- <div class="page page-red" id="page2">2</div>
- <!-- 侧边栏 -->
- <div class="page-slide">
- <div class="slide-item" data-target="page1">1</div>
- <div class="slide-item" data-target="page2">2</div>
- </div>
- </div>
- <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
- <script>
- $(function () {
- // 逻辑代码
- var current = $(".page.active");
- $(".slide-item").on("click", function(ele) {
- var target = $("#"+ $(ele.currentTarget).data("target"));
- if (target.hasClass('active')) {
- return ;
- }
- current.animate({
- marginTop: "100%"
- },
- 500,
- "swing",
- function () {
- current.removeClass('active');
- current.css("margin-top", 0);
- target.addClass('active');
- current = target;
- }
- );
- });
- });
- </script>
- </body>
- </html>
来源: http://blog.csdn.net/demon3182/article/details/79261632