02 - JavaScript APIs - 05.移动端网页特效

移动端网页特效

touch 触屏事件 / 触摸事件

概述

  • 移动端浏览器兼容性较好,不需考虑 JS 兼容性问题,可放心使用原生 JS 书写效果

常见触屏事件

  • touchstart【手指触摸到 DOM 元素时触发】【有自己的事件对象】
  • touchmove【手指在 DOM 元素上滑动时触发】【有自己的事件对象】
  • touchend【手指从 DOM 元素上移开时触发】【有自己的事件对象】
  • 示例
    <head>
        <style>
            div {
                width: 100px;
                height: 100px;
                background-color: pink;
            }
        </style>
    </head>
    
    <body>
        <div></div>
        <script>
            var div = document.querySelector('div');
            div.addEventListener('touchstart', function() {
                console.log('我摸了你');
            });
            div.addEventListener('touchmove', function() {
                console.log('我继续摸');
            });
            div.addEventListener('touchend', function() {
                console.log('轻轻的我走了');
            });
        </script>
    </body>
    

触摸事件对象 TouchEvent

  • 描述手指在触摸平面的状态变化的事件,可描述一 / 多个触点,使开发者检测触点的移动、增加和减少
  • touches【正在触摸屏幕的所有手指的一个列表】
  • targetTouched【正在触摸当前 DOM 元素上的手指的一个列表】【重点】
  • changedTouches【手指状态发生了改变的列表,从无到有,从有到无】

移动端拖动元素

  • e.preventDefault():阻止默认的屏幕滚动【因为手指移动会触发滚动屏幕】
  • 示例
    <head>
        <style>
            div {
                position: absolute;
                left: 0;
                width: 100px;
                height: 100px;
                background-color: pink;
            }
        </style>
    </head>
    
    <body>
        <div></div>
        <script>
            var div = document.querySelector('div');
            var startX = 0;  // 手指初始坐标
            var startY = 0;
            var x = 0;  // 盒子原来的位置
            var y = 0;
            
            div.addEventListener('touchstart', function(e) {
                startX = e.targetTouches[0].pageX;
                startY = e.targetTouches[0].pageY;
                x = this.offsetLeft;
                y = this.offsetTop;
            });
            div.addEventListener('touchmove', function(e) {
                var moveX = e.targetTouches[0].pageX - startX;
                var moveY = e.targetTouches[0].pageY - startY;
                this.style.left = x + moveX + 'px';
                this.style.top = y + moveY + 'px';
                e.preventDefault();  // 阻止屏幕滚动的默认行为
            });
        </script>
    </body>
    

移动端常见特效

移动端轮播图

// index.js
window.addEventListener('load', function() {
    var focus = document.querySelector('.focus');
    var ul = focus.children[0];
    var ol = focus.children[1];
    var w = focus.offsetWidth;
    var index = 0;
    
    var timer = setInterval(function() {  // 自动轮播图片
        index++;
        var translatex = -index * w;
        ul.style.transition = 'all .3s';  // css3 过渡效果
        ul.style.transform = 'translateX(' + translatex + 'px)';
    }, 2000);
    
    ul.addEventListener('transitionend', function() {  // 检测过渡完成事件
        if (index >= 3) {  // 【无缝滚动】【此处判断条件应大于等于3,若仅为等于3,当新开一个页面后,轮播图 index 可能会无限增大,故图片轮空(浏览器运行原理:切换 tab,窗口失去焦点,渲染停止)】
            index = 0;
            ul.style.transition = 'none';  // 去掉过渡效果,让 ul 快速跳到目标位置
            var translatex = -index * w;  // 用最新索引号乘宽度,滚动图片
            ul.style.transform = 'translateX(' + translatex + 'px)';
        } else if (index < 0) {
            index = 2;
            ul.style.transition = 'none';
            var translatex = -index * w;
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }
		// 跟随变化的小圆点
        ol.querySelector('.current').classList.remove('current');
        ol.children[index].classList.add('current');
    });

    var startX = 0;
    var moveX = 0;
    var flag = false;
    ul.addEventListener('touchstart', function(e) {
        startX = e.targetTouches[0].pageX;
        clearInterval(timer);
    });
    ul.addEventListener('touchmove', function(e) {
        moveX = e.targetTouches[0].pageX - startX;
        var translatex = -index * w + moveX;
        ul.style.transition = 'none';
        ul.style.transform = 'translateX(' + translatex + 'px)';
        flag = true;  // 用户手指移动过再判断,否则不判断。提高效率
        e.preventDefault();  // 阻止滚动屏幕的行为
    });
    ul.addEventListener('touchend', function(e) {
        if (flag) {
            if (Math.abs(moveX) > 50) {
                if (moveX > 0) {
                    index--;
                } else {
                    index++;
                }
                var translatex = -index * w;
                ul.style.transition = 'all .3s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            } else {  // 直接回弹
                var translatex = -index * w;
                ul.style.transition = 'all .1s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            }
        }
        clearInterval(timer);  // 开定时器前先清除
        timer = setInterval(function() {
            index++;
            var translatex = -index * w;
            ul.style.transition = 'all .3s';
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }, 2000);
    });

    // 返回顶部
    var goBack = document.querySelector('.goBack');
    var nav = document.querySelector('nav');
    window.addEventListener('scroll', function() {
        if (window.pageYOffset >= nav.offsetTop) {
            goBack.style.display = 'block';
        } else {
            goBack.style.display = 'none';
        }
    });
    goBack.addEventListener('click', function() {
        window.scroll(0, 0);
    })
})

// index.html
<!-- 返回顶部模块 -->
<div class="goBack"></div>
<!-- 焦点图模块 -->
<div class="focus">
	<ul>
	    <li><img src="upload/focus3.jpg" alt=""></li>
	    <li><img src="upload/focus1.jpg" alt=""></li>
	    <li><img src="upload/focus2.jpg" alt=""></li>
	    <li><img src="upload/focus3.jpg" alt=""></li>
	    <li><img src="upload/focus1.jpg" alt=""></li>
	</ul>
	<!-- 小圆点 -->
    <ol>
	     <li class="current"></li>
	     <li></li>
	     <li></li>
   	</ol>
</div>

// index.css
.goBack {
    display: none;
    position: fixed;
    bottom: 50px;
    right: 20px;
    width: 38px;
    height: 38px;
    background: url(../images/back.png) no-repeat;
    background-size: 38px 38px;
}
.focus {
    position: relative;
    padding-top: 44px;
    overflow: hidden;
}
.focus img {
    width: 100%;  // 此处的 100% 以父元素为基准
}
.focus ul {
    overflow: hidden;
    width: 500%;
    margin-left: -100%;  // 注意此处需左移
}
.focus ul li {
    float: left;  // 想将五张图放在一行中,每张图片需加浮动
    width: 20%;  // 儿子li没有给定宽度,所以li宽度跟着ul宽度走,导致图片变宽,因此li宽为20%
}
.focus ol {
    position: absolute;
    bottom: 5px;
    right: 5px;
    margin: 0;
}
.focus ol li {
    display: inline-block;
    width: 5px;
    height: 5px;
    background-color: #fff;
    list-style: none;
    border-radius: 2px;
    transition: all .3s;
}
.focus ol li.current {
    width: 15px;
}

要点

  • 移动端动画尽量使用 css3【js + css3】
  • 移动端轮播图,首尾都要加图片
    PC端轮播图,只有尾部加图片
  • transitionend 【检测过渡完成事件】

classList 属性

  • HTML5 新增属性,返回元素的类名【ie10+支持】
  • 用于在元素中添加,移除及切换 CSS 类
  • element.classList.add('类名')【添加类】【类名不加.
    element.classList.remove('类名')【移除类】【类名不加.
    element.classList.toggle('类名')【切换类】【类名不加.
  • className【追加类名,会覆盖】
    classList【追加类名,不会覆盖】
  • 示例
    <head>
        <style>
            .bg {
                background-color: black;
            }
        </style>
    </head>
    
    <body>
        <div class="one two"></div>
        <button> 开关灯</button>
        <script>
            var div = document.querySelector('div');
            // console.log(div.classList[1]);
            div.classList.add('three');
            div.classList.remove('one');
            
            var btn = document.querySelector('button');
            btn.addEventListener('click', function() {
                document.body.classList.toggle('bg');
            })
        </script>
    </body>
    

click 延时解决方案

  • 移动端 click 事件会有 300ms 延时,原因是移动端屏幕双击会缩放页面
  • 解决方案
    1.禁用缩放 <meta name="viewport" content="user-scalable=no">
    2.自己封装此事件
    function tap (obj, callback) {
    	var isMove = false;
    	var startTime = 0;
     	obj.addEventListener('touchstart', function (e) {
     		startTime = Date.now();
     	});
     	obj.addEventListener('touchmove', function (e) {
     		isMove = true;
     	});
     	obj.addEventListener('touchend', function (e) {
     		if (!isMove && (Date.now() - startTime) < 150) {
     			callback && callback();
     		}
     		isMove = false;
     		startTime = 0;
     	});
    }
    
    tap(div, function() {// 执行代码 });
    
    3.使用插件【fastclick】【相较于1.2的优点是,页面中所有元素的 click 延迟都被取消】

移动端常用开发插件

插件概念

  • JS 插件是 js 文件,遵循一定规范编写,方便程序展示效果,拥有特定功能,且方便调用。如轮播图和瀑布流插件
  • 特点:一般是为解决某问题专门存在,功能单一,且比较小
  • GitHub官网地址:https://github.com/ftlabs/fastclick

使用插件

  • 用法
    1.引入 js 插件文件
    2.按照规定语法使用
  • 总结
    1.确认插件实现的功能
    2.去官网查看使用说明
    3.下载插件
    4.打开 demo 实例文件,查看需要引入的相关文件,并且引入
    5.复制 demo 实例文件中的结构 html,样式 css 以及 js 代码
  • 示例
    // fastclick 插件
    <head>
        <style>
            div {
                width: 50px;
                height: 50px;
                background-color: pink;
            }
        </style>
        <script src="fastclick.js"></script>
    </head>
    
    <body>
        <div></div>
        <script>
            if ('addEventListener' in document) {
                document.addEventListener('DOMContentLoaded', function() {
                    FastClick.attach(document.body);
                }, false);
            }
            var div = document.querySelector('div');
        </script>
    </body>
    
    // swiper 插件
    window.addEventListener('load', function() {
        var swiper = new Swiper('.swiper-container', {
            spaceBetween: 30,
            centeredSlides: true,
            autoplay: {
                delay: 5000,
                disableOnInteraction: false,
            },
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
        });
    })
    
    // index.css
    // 可更改自定义css的权重,覆盖插件样式
    .swiper-pagination-bullet {
        background: #fff!important;
    }
    

常用插件

  • https://www.swiper.com.cn/【swiper】
  • http://www.superslide2.com/【superslide】
  • https://github.com/cubiq/iscroll【scroll】
  • zy.media.js【视频插件】
    ①H5 提供了 video 标签,浏览器的支持情况不同
    ②不同的视频格式文件,可通过 source 解决
    ③外观样式、暂停、播放、全屏只能通过写代码解决
    // 传统写法
    <head>
        <link rel="stylesheet" href="zy.media.min.css">
        <script src="zy.media.min.js"></script>
        <style type="text/css">
            #modelView {
                background-color: #DDDDDD;
                z-index: 0;
                opacity: 0.7;
                height: 100%;
                width: 100%;
                position: relative;
            }
            .playvideo {
                padding-top: auto;
                z-index: 9999;
                position: relative;
                width: 300px;
                height: 200px;
            }
            .zy_media {
                z-index: 999999999
            }
        </style>
    </head>
    
    <body>
        <div class="playvideo">
            <div class="zy_media">
                <video data-config='{"mediaTitle": "小蝴蝶"}'>
                	<source src="mov.mp4" type="video/mp4">
                    您的浏览器不支持HTML5视频
            	</video>
     		</div>
            <div id="modelView">&nbsp;</div>
    	</div>
        <script>
            zymedia('video', {
                autoplay: false
            });
        </script>
    </body>
    

移动端常用开发框架

框架概述

  • 一套会基于自身特点向用户提供一套较为完整解决方案的架构。框架的控制权在框架本身,使用者要按照框架所规定的某种规范进行开发
  • 插件: 小而专一,某个功能的解决方案。常见的有 Bootstrap、Vue、Angular、React 等
    框架:大而全,一整套解决方案。常见的有 swiper、superslide、iscroll 等【PC端 / 移动端】

Bootstrap

  • 简洁、直观、强悍的前端开发框架,让 web 开发更迅速、简单
  • Bootstrap JS插件使用步骤:
    1.引入相关 js 文件
    2.复制 HTML 结构
    3.修改对应样式
    4.修改相应 JS 参数
  • bootstrap 轮播图
    <head>
        <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
        <script src="bootstrap/js/jquery.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>  // bootstrap 依赖于 jquery
        <style>
            .focus {
                width: 800px;
                height: 300px;
                background-color: pink;
                margin: 100px auto;
            }
            .carousel,
            .carousel img {
                width: 100%;
                height: 300px!important;
            }
        </style>
    </head>
    
    <body>
        <div class="focus">
            <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
                <!-- Indicators 小圆点 -->
                <ol class="carousel-indicators">
                    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
                    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
                    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
                </ol>
    
                <!-- Wrapper for slides 轮播图片 -->
                <div class="carousel-inner" role="listbox">
                    <div class="item active">
                        <img src="upload/banner.dpg" alt="...">
                        <div class="carousel-caption">
                            这是我的图片1
                        </div>
                    </div>
                    <div class="item">
                        <img src="upload/banner1.dpg" alt="...">
                        <div class="carousel-caption">
                            这是我的图片2
                        </div>
                    </div>
                    <div class="item">
                        <img src="upload/banner2.dpg" alt="...">
                        <div class="carousel-caption">
                            这是我的图片3
                        </div>
                    </div>
                    ...
                </div>
    
                <!-- Controls 左右箭头 -->
                <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
                    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                    <span class="sr-only">Previous</span>
                </a>
                <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
                    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                    <span class="sr-only">Next</span>
                </a>
            </div>
        </div>
        <script>
            $('.carousel').carousel({
                interval: 2000
            })
        </script>
    </body>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值