Web前端学习笔记——HTML5与CSS3之H5-DOM扩展、H5新增API

H5-dom扩展

获取元素
document.getElementsByClassName ('class'); 
//通过类名获取元素,以伪数组形式存在。

document.querySelector('selector');
//通过CSS选择器获取元素,符合匹配条件的第1个元素。

document.querySelectorAll('selector'); 
//通过CSS选择器获取元素,以伪数组形式存在。
类名操作
Node.classList.add('class'); 
//添加class

Node.classList.remove('class'); 
//移除class

Node.classList.toggle('class'); 
//切换class,有则移除,无则添加

Node.classList.contains('class'); 
//检测是否存在class
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul {
            list-style: none;
        }

        li {
            width: 100px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: #fff;
            background: green;
            float: left;
            cursor: pointer;
        }

        li.active {
            background: red;
        }
    </style>
</head>
<body>
<ul>
    <li>菜单1</li>
    <li class="active">菜单2</li>
    <li>菜单3</li>
    <li>菜单4</li>
</ul>
<!--<button>切换类</button>-->
<!--
1. jquery操作类的方法:addClass() removeClass() toggleClass() hasClass()
2. h5也有类似的api 基于一个对象classList的方法 add() remove() toggle() contains()
-->
<!--<script>
    var dom = document.querySelector('li:nth-child(2)');
    /*1.获取类*/
    console.log(dom.classList);
    /* DOM.classList  获取的是这个DOM元素上的所有class */
    /*2.操作类*/
    dom.classList.add('blue');
    dom.classList.remove('red');

    document.querySelector('button').onclick = function () {
        dom.classList.toggle('toggle');
        console.log(dom.classList.contains('red'));
    }
</script>-->
<script>
    window.onload = function () {
        /*切换当前样式的效果*/
        document.querySelector('ul').onclick = function (e) {
            /*当前的LI*/
            var currentLi = e.target;
            /*如果已经选中 程序停止*/
            if(currentLi.classList.contains('active')) return false;
            /*如果没有选中*/
            /*之前的去除*/
            document.querySelector('li.active').classList.remove('active');
            /*在给当前的加上*/
            currentLi.classList.add('active');
        }
    }
</script>
</body>
</html>
自定义属性

在HTML5中我们可以自定义属性,其格式如下data-*=""


<div id="demo" data-my-name="itcast" data-age="10">
<script>
/*
  Node.dataset是以对象形式存在的,当我们为同一个DOM节点指定了多个自定义属性时,
  Node.dataset则存储了所有的自定义属性的值。
  */
var demo = document.querySelector(反馈);
//获取
//注:当我们如下格式设置时,则需要以驼峰格式才能正确获取
var name = demo.dataset['myName'];
var age = demo.dataset['age'];
//设置
demo.dataset['name'] = 'web developer';
<script/>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--
1.自定义属性  data-* 自定义属性
2.获取元素的自定义属性  jquery获取方式  $('div').data('自定义属性的名称)
3.自定义属性的名称是什么? data-user==>user data-user-name==>userName
4.命名规则 遵循驼峰命名法
5.获取元素的自定义属性 h5的方式  dataset  自定义属性的集合
-->
<div data-user="wl" data-user-age="18"></div>
<script src="../3d切割轮播图/jquery.min.js"></script>
<script>
    var div = document.querySelector('div');
    /*获取所有  $('div').data() */
    var set = div.dataset;
    /*获取单个自定义属性  $('div').data('user')*/
    /*var user = set.user;
    var user = set['user'];*/

    /*设置单个属性  $('div').data('user','gg')*/
    set.user = 'gg';

    /*jquery的data() 操作内存*/
    /*H5的dataset     操作dom*/

</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        ul:first-child {
            list-style: none;
        }

        ul:first-child li {
            width: 100px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: #fff;
            background: green;
            float: left;
            cursor: pointer;
        }

        ul:first-child li.active {
            background: red;
        }

        .box li{
            width: 400px;
            height: 400px;
            background: pink;
            display: none;
        }
        .box li.show{
            display: block;
        }
    </style>
</head>
<body>
<ul class="nav">
    <!--在渲染的时候  大小的属性会转换成小写 -->
    <li data-content-id="content01">菜单1</li>
    <li data-content-id="content02" class="active">菜单2</li>
    <li data-content-id="content03">菜单3</li>
    <li data-content-id="content04">菜单4</li>
</ul>
<ul class="box">
    <li id="content01">内容1</li>
    <li id="content03">内容3</li>
    <li id="content04">内容4</li>
    <li id="content02" class="show">内容2</li>
</ul>
<!-- css序号选择器伪类选择器  E:first-child-->
<!-- 查找顺序:
通过E确定父元素
通过父元素找到所有的子元素
再去找第一个子元素
找到第一个子元素之后再去匹配类型是不是E  不是:无效选择器
ul:last-child
-->
<script>
    /*tab切换*/
    window.onload = function () {
        document.querySelector('.nav').onclick = function (e) {
            var currentLi = e.target;
            /*已经选中 停止操作*/
            if(currentLi.classList.contains('active')) return false;

            var oldLi = document.querySelector('.nav li.active');
            /*1.更改样式*/
            oldLi.classList.remove('active');
            currentLi.classList.add('active');
            /*2.根据选中的页签去显示对应的内容*/
            /*隐藏之前的*/
            var oldContent = document.querySelector('#'+oldLi.dataset.contentId);
            oldContent.classList.remove('show');
            /*显示当前的*/
            var currentContent = document.querySelector('#'+currentLi.dataset.contentId);
            currentContent.classList.add('show');
        }
    }
</script>
</body>
</html>

3D切割轮播图

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

        .box {
            width: 560px;
            height: 300px;
            margin: 100px auto 0;
            border: 1px solid #ccc;
            position: relative;
        }

        .box .imageBox {
            list-style: none;
            width: 100%;
            height: 100%;
            /*overflow: hidden;*/
            /*视距:呈现近大远小效果 */
            /*perspective: 500px;*/
            /*3d呈现*/
            transform-style: preserve-3d;
        }

        .box .imageBox li {
           /* width: 100%;
            height: 100%;
            float: left;*/
            width: 112px;
            height: 100%;
            float: left;
            position: relative;
            /*视距:呈现近大远小效果 */
            /*perspective: 500px;*/
            /*3d呈现*/
            transform-style: preserve-3d;
            /*加过渡*/
            transition:all 1s;
        }
        .box .imageBox li span{
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: url("images/1.jpg") no-repeat;
        }

        /*拼接立体容器*/
        /*1.立体容器旋转中心要在电脑平面上*/
        /*2.立体容器每一个面的图片正面朝外*/
        .box .imageBox li span:nth-child(1){
            background-image: url("images/1.jpg");
            transform: translateZ(150px);
        }
        .box .imageBox li span:nth-child(2){
            background-image: url("images/2.jpg");
            /*旋转过后轴也会旋转::::::*/
            transform: rotateX(90deg) translateZ(150px);
        }
        .box .imageBox li span:nth-child(3){
            background-image: url("images/3.jpg");
            transform: rotateX(180deg) translateZ(150px);
        }
        .box .imageBox li span:nth-child(4){
            background-image: url("images/4.jpg");
            transform: rotateX(270deg) translateZ(150px);
        }

        /*拼接背景*/
        .box .imageBox li:nth-child(1) span{
            background-position: 0 0;
        }
        .box .imageBox li:nth-child(2) span{
            background-position: -112px 0;
        }
        .box .imageBox li:nth-child(3) span{
            background-position: -224px 0;
        }
        .box .imageBox li:nth-child(4) span{
            background-position: -336px 0;
        }
        .box .imageBox li:nth-child(5) span{
            background-position: -448px 0;
        }
        /*.box .imageBox li img{
            display: block;
            width: 100%;
            height: 100%;
        }*/
        .box .left,
        .box .right{
            position: absolute;
            width: 50px;
            height: 70px;
            background: rgba(0,0,0,.2);
            top:115px;
            text-align: center;
            line-height: 70px;
            font-size: 20px;
            color: #fff;
            text-decoration: none;
            font-weight: bold;
        }
        .box .right{
            right: 0;
        }
    </style>
</head>
<body>
<!--1.完成这个例子要用到什么知识-->
<!--2.回顾一下3d转换-->
<!--3.轴的正方向,translate rotate 3d转换属性-->
<!--4.rotateX rotateY rotateZ 旋转方向  方法方式套路-->
<!--4.1 顺着轴的正方向看  顺时针旋转是负角度  逆时针旋转是正角度-->
<!--5.过渡完成动画-->
<!--6.通过jquery辅助操作-->
<div class="box">
    <ul class="imageBox">
        <li>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </li>
        <li>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </li>
        <li>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </li>
        <li>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </li>
        <li>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </li>
    </ul>
    <!-- 转义符 \  实体 &lt; -->
    <a class="left" href="javascript:;">&lt;</a>
    <a class="right" href="javascript:;">&gt;</a>
</div>
<script src="jquery.min.js"></script>
<script>
    $(function () {
        /*1.点击切换图片*/
        /*定义一个索引*/
        /*看第2张图 -90deg  看第4张图 90deg */
        var index = 0;
        /*开关*/
        var flag = true;
        /*2.点击左边的按钮 上一张*/
        $('.left').on('click',function () {

            if(!flag) return false;
            flag = false;

            index --;
            console.log(index);
            var angle = - index * 90;
            $('li').css('transform','rotateX('+angle+'deg)').each(function (i,item) {
                /*设置不同的延时*/
                $(this).css('transition-delay',i*0.25+'s');
            });
        });
        /*3.点击右边的按钮 下一张*/
        $('.right').on('click',function () {

            if(!flag) return false;
            flag = false;

            index ++;
            console.log(index);
            var angle = - index * 90;
            $('li').css('transform','rotateX('+angle+'deg)').each(function (i,item) {
                /*设置不同的延时*/
                $(this).css('transition-delay',i*0.25+'s');
            });
        });
        /*4.优化 重复点击的时候动画会层叠的执行  节流阀 */
        $('li:last').on('transitionend',function () {
            /*最后一部分张图片旋转完毕*/
            flag = true;
        });

    });
</script>
</body>
</html>

H5-新增API

全屏方法

HTML5规范允许用户自定义网页上任一元素全屏显示。

  • Node.requestFullScreen() 开启全屏显示
  • Node.cancelFullScreen() 关闭全屏显示
  • 由于其兼容性原因,不同浏览器需要添加前缀如:
    webkit内核浏览器:webkitRequestFullScreen、webkitCancelFullScreen,如chrome浏览器。
    Gecko内核浏览器:mozRequestFullScreen、mozCancelFullScreen,如火狐浏览器。
  • document.fullScreen检测当前是否处于全屏
    不同浏览器需要添加前缀
    document.webkitIsFullScreen、document.mozFullScreen
多媒体

自定义播放器

方法

方法 描述
addTextTrack() 向音频/视频添加新的文本轨道
canPlayType() 检测浏览器是否能播放指定的音频/视频类型
load() 重新加载音频/视频元素
play() 开始播放音频/视频
pause() 暂停当前播放的音频/视频

属性

属性 描述
audioTracks 返回表示可用音轨的 AudioTrackList 对象
autoplay 设置或返回是否在加载完成后随即播放音频/视频
buffered 返回表示音频/视频已缓冲部分的 TimeRanges 对象
controller 返回表示音频/视频当前媒体控制器的 MediaController 对象
controls 设置或返回音频/视频是否显示控件(比如播放/暂停等)
crossOrigin 设置或返回音频/视频的 CORS 设置
currentSrc 返回当前音频/视频的 URL
currentTime 设置或返回音频/视频中的当前播放位置(以秒计)
defaultMuted 设置或返回音频/视频默认是否静音
defaultPlaybackRate 设置或返回音频/视频的默认播放速度
duration 返回当前音频/视频的长度(以秒计)
ended 返回音频/视频的播放是否已结束
error 返回表示音频/视频错误状态的 MediaError 对象
loop 设置或返回音频/视频是否应在结束时重新播放
mediaGroup 设置或返回音频/视频所属的组合(用于连接多个音频/视频元素)
muted 设置或返回音频/视频是否静音
networkState 返回音频/视频的当前网络状态
paused 设置或返回音频/视频是否暂停
playbackRate 设置或返回音频/视频播放的速度
played 返回表示音频/视频已播放部分的 TimeRanges 对象
preload 设置或返回音频/视频是否应该在页面加载后进行加载
readyState 返回音频/视频当前的就绪状态
seekable 返回表示音频/视频可寻址部分的 TimeRanges 对象
seeking 返回用户是否正在音频/视频中进行查找
src 设置或返回音频/视频元素的当前来源
startDate 返回表示当前时间偏移的 Date 对象
textTracks 返回表示可用文本轨道的 TextTrackList 对象
videoTracks 返回表示可用视频轨道的 VideoTrackList 对象
volume 设置或返回音频/视频的音量

事件

事件 描述
abort 当音频/视频的加载已放弃时
canplay 当浏览器可以播放音频/视频时
canplaythrough 当浏览器可在不因缓冲而停顿的情况下进行播放时
durationchange 当音频/视频的时长已更改时
emptied 当目前的播放列表为空时
ended 当目前的播放列表已结束时
error 当在音频/视频加载期间发生错误时
loadeddata 当浏览器已加载音频/视频的当前帧时
loadedmetadata 当浏览器已加载音频/视频的元数据时
loadstart 当浏览器开始查找音频/视频时
pause 当音频/视频已暂停时
play 当音频/视频已开始或不再暂停时
playing 当音频/视频在已因缓冲而暂停或停止后已就绪时
progress 当浏览器正在下载音频/视频时
ratechange 当音频/视频的播放速度已更改时
seeked 当用户已移动/跳跃到音频/视频中的新位置时
seeking 当用户开始移动/跳跃到音频/视频中的新位置时
stalled 当浏览器尝试获取媒体数据,但数据不可用时
suspend 当浏览器刻意不获取媒体数据时
timeupdate 当目前的播放位置已更改时
volumechange 当音量已更改时
waiting 当视频由于需要缓冲下一帧而停止
  • index.html
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>视频播放</title>
    <!--字体图标库-->
    <link rel="stylesheet" href="css/font-awesome.css"/>
    <link rel="stylesheet" href="css/player.css"/>
</head>
<body>
<figure>
    <figcaption>视频播放器</figcaption>
    <div class="player">
        <video src="./video/fun.mp4"></video>
        <div class="controls">
            <!--播放/暂停-->
            <a href="javascript:;" class="switch fa fa-play"></a>
            <!--播放进度-->
            <div class="progress">
                <div class="line"></div>
                <div class="bar"></div>
            </div>
            <!--当前播放时间/播放总时长-->
            <div class="timer">
                <span class="current">00:00:00</span> / <span class="total">00:00:00</span>
            </div>
            <!--全屏/取消全屏-->
            <a href="javascript:;" class="expand fa fa-arrows-alt"></a>
        </div>
    </div>
</figure>
<script src="./js/jquery.min.js"></script>
<script>
    $(function () {
        /*获取需要操作的元素*/
        var $video = $('video');
        /*因为api是属于原生的dom元素的*/
        var video = $video.get(0);

        /*播放和暂停*/
        var $switch = $('.switch');
        /*总时长*/
        var $total = $('.total');
        /*进度条*/
        var $line = $('.line');
        /*当前播放时间*/
        var $current = $('.current');
        /*全屏按钮*/
        var $expand = $('.expand');
        /*灰色进度条*/
        var $bar = $('.bar');

        var formatTime = function (time) {
            /*00:00:00*/
            var h = Math.floor(time/3600);
            var m = Math.floor(time%3600/60);
            var s = Math.floor(time%60);
            return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)
        }

        /*1. 需要在加载是时候  显示加载状态*/
        /*当前视频加载到可以播放了就可以隐藏这个状态*/
        video.oncanplay = function () {
            $video.show();
            /*显示总时间*/
            var timeStr = formatTime(video.duration);
            /*6. 总时间显示*/
            $total.html(timeStr);
        }

        /*2. 播放*//*3. 暂停*/
        $switch.on('click',function () {
            if($switch.hasClass('fa-play')){
                video.play();
                $switch.removeClass('fa-play').addClass('fa-pause');
            }else{
                video.pause();
                $switch.removeClass('fa-pause').addClass('fa-play');
            }
        });

        /*4. 进度条显示*/
        video.ontimeupdate = function () {
            //console.log('当前播放时间:'+video.currentTime);
            /*计算  进度条的宽度根据  当前播放时间/总时间  */
            var p = video.currentTime/video.duration*100+'%';
            $line.css('width',p);
            /*5. 播放时间显示*/
            $current.html(formatTime(video.currentTime));
        }
        /*7. 全屏操作*/
        $expand.on('click',function () {
            if($(this).hasClass('fa-arrows-alt')){
                video.webkitRequestFullScreen();
                $(this).removeClass('fa-arrows-alt').addClass('fa-compress');
            }else{
                document.webkitCancelFullScreen();
                $(this).addClass('fa-arrows-alt').removeClass('fa-compress');
            }

        })
        /*8. 视频播放完成重置播放*/
        video.onended = function () {
            video.currentTime = 0;
            $switch.removeClass('fa-pause').addClass('fa-play');
        }
        /*9. 跃进功能*/
        $bar.on('click',function (e) {
            /*获取点击的位置距离进度条左侧的距离*/
            var p = e.offsetX/$bar.width();
            var goTime = p * video.duration;
            video.currentTime = goTime;
        })
    });
</script>
</body>
</html>
  • player.css
body {
    padding: 0;
    margin: 0;
    font-family: 'microsoft yahei', 'Helvetica', simhei, simsun, sans-serif;
    background-color: #F7F7F7;
}
a {
    text-decoration: none;
}
figcaption {
    font-size: 24px;
    text-align: center;
    margin: 20px;
}
.player {
    width: 720px;
    height: 360px;
    margin: 0 auto;
    border-radius: 4px;
    background: #000 url(../images/loading.gif) center/300px no-repeat;
    position: relative;
    text-align: center;
}
video {
    display: none;
    height: 100%;
    margin: 0 auto;
}
/*全屏操作后  自带的控制栏会显示  在显示的时候隐藏*/
video::-webkit-media-controls {
    display: none !important;
}
.controls {
    width: 700px;
    height: 40px;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 4px;
    position: absolute;
    left: 50%;
    margin-left: -350px;
    bottom: 5px;
    /*比全屏的状态下的视频元素高*/
    z-index: 100000000000;
    opacity: 1;
}
.player:hover .controls {
    opacity: 1;
}
/*播放/暂停*/
.controls .switch {
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    color: #FFF;
    position: absolute;
    top: 11px;
    left: 11px;
}
/*全屏按钮*/
.controls .expand {
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    color: #FFF;
    position: absolute;
    right: 11px;
    top: 11px;
}
/*进度条*/
.progress {
    width: 430px;
    height: 10px;
    border-radius: 3px;
    overflow: hidden;
    background-color: #555;
    cursor: pointer;
    position: absolute;
    top: 16px;
    left: 45px;
}
/*下载进度*/
.progress .loaded {
    width: 0;
    height: 100%;
    background-color: #999;
}
/*播放进度*/
.progress .line {
    width: 0;
    height: 100%;
    background-color: #FFF;
    position: absolute;
    top: 0;
    left: 0;
}
.progress .bar {
    width: 100%;
    height: 100%;
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
}
/*时间*/
.timer {
    height: 20px;
    line-height: 20px;
    position: absolute;
    left: 490px;
    top: 11px;
    color: #FFF;
    font-size: 14px;
}
地理定位

在HTML规范中,增加了获取用户地理信息的API,
这样使得我们可以基于用户位置开发互联网应用,
即基于位置服务 (Location Base Service)

  • 获取当前地理信息
navigator.geolocation.getCurrentPosition(successCallback, errorCallback) 
  • 重复获取当前地理信息
navigator. geolocation.watchPosition(successCallback, errorCallback)
  • 当成功获取地理信息后,会调用succssCallback,并返回一个包含位置信息的对象position。
    position.coords.latitude纬度
    position.coords.longitude经度
    position.coords.accuracy精度
    position.coords.altitude海拔高度
  • 当获取地理信息失败后,会调用errorCallback,并返回错误信息error
  • 在现实开发中,通过调用第三方API(如百度地图)来实现地理定位信息,这些API都是基于用户当前位置的,并将用位置位置(经/纬度)当做参数传递,就可以实现相应的功能。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Geolocation</title>
    <style type="text/css">
        html,body {
            height: 100%
        }
        body {
            margin: 0;
            padding: 0;
        }
        #container {
            height: 100%
        }
    </style>
</head>
<body>
<div id="container"></div>
<!-- 引入百度javascript版 API -->
<script src="http://api.map.baidu.com/api?v=2.0&ak=	0A5bc3c4fb543c8f9bc54b77bc155724"></script>
<script>

    /*h5  geolocation */
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function (position) {
            /*获取定位成功回调函数*/
            /*定位数据*/
            console.log(position);
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;

            // 这些都是写死
            var map = new BMap.Map("container"); // container表示显示哪个容器
            // 把经度纬度传给百度
            /*40.1691162668,116.6348530780*/
            var point = new BMap.Point(longitude, latitude);
            //默认的比例
            map.centerAndZoom(point, 20);
            //添加鼠标滚动缩放
            map.enableScrollWheelZoom();
            // 只写上面三行就可出现地图了,并且会定位
            // 定义好了一个图片标记
            var myIcon = new BMap.Icon("1.png", new BMap.Size(128, 128));
            // 创建标注
            var marker = new BMap.Marker(point, {icon: myIcon});
            map.addOverlay(marker);
            //点击地图,获取经纬度坐标
            map.addEventListener("click",function(e){
                console.log("经度坐标:"+e.point.lng+" 纬度坐标:"+e.point.lat);
            });
        }, function (error) {
            /*获取定位失败回调函数*/
            /*失败原因*/
            console.log(error)
        });
    }

    // 这些都是写死
    var map = new BMap.Map("container"); // container表示显示哪个容器
    // 把经度纬度传给百度
    /*40.1691162668,116.6348530780*/
    var point = new BMap.Point(116.6348530780, 40.1691162668);
    //默认的比例
    map.centerAndZoom(point, 20);
    //添加鼠标滚动缩放
    map.enableScrollWheelZoom();
    // 只写上面三行就可出现地图了,并且会定位
    // 定义好了一个图片标记
    var myIcon = new BMap.Icon("1.png", new BMap.Size(128, 128));
    // 创建标注
    var marker = new BMap.Marker(point, {icon: myIcon});
    map.addOverlay(marker);
    //点击地图,获取经纬度坐标
    map.addEventListener("click",function(e){
        console.log("经度坐标:"+e.point.lng+" 纬度坐标:"+e.point.lat);
    });

</script>
</body>
</html>
本地存储

随着互联网的快速发展,基于网页的应用越来越普遍,
同时也变的越来越复杂,为了满足各种各样的需求,会经常性在本地存储大量的数据,
HTML5规范提出了相关解决方案。

  • 特性
    • 设置、读取方便
    • 容量较大,sessionStorage约5M、localStorage约20M
    • 只能存储字符串,可以将对象JSON.stringify() 编码后存储
  • window.sessionStorage
    • 生命周期为关闭浏览器窗口
    • 在同一个窗口(页面)下数据可以共享
  • window.localStorage
    • 永久生效,除非手动删除(服务器方式访问然后清除缓存)
    • 可以多窗口(页面)共享
  • 方法
    • setItem(key, value) 设置存储内容
    • getItem(key) 读取存储内容
    • removeItem(key) 删除键值为key的存储内容
    • clear() 清空所有存储内容
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>首页</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body{
            margin-left: 300px;
        }
        ul{
            list-style: none;
        }
        ul li,div{
            width: 250px;
            padding: 10px 0;
            margin-left: 10px;
            border-bottom: 1px dashed #ccc;
            height: 20px;
        }
        a{
            float: right;
        }
        input{
            padding: 5px;
            margin: 10px;
        }
    </style>
</head>
<body>
<input type="search" placeholder="输入搜索关键字"/>
<input type="button" value="搜索"/>
<div><a href="javascript:;">清空搜索记录</a></div>
<ul>
    <li>没有搜索记录</li>
    <li><span>手机</span><a href="javascript:;">删除</a></li>
    <li><span>手机</span><a href="javascript:;">删除</a></li>
    <li><span>手机</span><a href="javascript:;">删除</a></li>
    <li><span>手机</span><a href="javascript:;">删除</a></li>
    <li><span>手机</span><a href="javascript:;">删除</a></li>
</ul>
<script src="jquery.min.js"></script>
<script>
    $(function () {
        /*1.使用json数据存储搜索历史记录*/
        /*2.预设一个key   historyList */
        /*3.数据格式列表 存的是json格式的数组*/
        /*4. [电脑,手机,。。。。]*/

        /*1.默认根据历史记录渲染历史列表*/
        var historyListJson = localStorage.getItem('historyList') || '[]';
        var historyListArr = JSON.parse(historyListJson);
        /*获取到了数组格式的数据*/
        var render = function () {
            /*$.each(function(i,item){}) for() for in */
            /* forEach 遍历函数  只能数组调用  回到函数(所有对应的值,索引)*/
            var html = '';
            historyListArr.forEach(function (item,i) {
                html += '<li><span>'+item+'</span><a data-index="'+i+'" href="javascript:;">删除</a></li>';
            });
            html = html || '<li>没有搜索记录</li>';
            $('ul').html(html);
        }
        render();

        /*2.点击搜索的时候更新历史记录渲染列表*/
        $('[type="button"]').on('click',function () {
            var key = $.trim($('[type=search]').val());
            if(!key){
                alert('请输入搜索关键字');
                return false;
            }
            /*追加一条历史*/
            historyListArr.push(key);
            /*保存*/
            localStorage.setItem('historyList',JSON.stringify(historyListArr));
            /*渲染一次*/
            render();
            $('[type=search]').val('');
        });

        /*3.点击删除的时候删除对应的历史记录渲染列表*/
        $('ul').on('click','a',function () {
            var index = $(this).data('index');
            /*删除*/
            historyListArr.splice(index,1);
            /*保存*/
            localStorage.setItem('historyList',JSON.stringify(historyListArr));
            /*渲染一次*/
            render();
        });

        /*4.点击清空的时候清空历史记录渲染列表*/
        $('div a').on('click',function () {
            /*清空*/
            historyListArr = [];
            /*慎用  清空网上的所有本地存储*/
            //localStorage.clear();
            //localStorage.removeItem('historyList');
            localStorage.setItem('historyList','');
            render();
        });
    });
</script>
</body>
</html>
历史管理

提供window.history,对象我们可以管理历史记录,
可用于单页面应用,Single Page Application,可以无刷新改变网页内容。

  • pushState(data, title, url) 追加一条历史记录
    • data用于存储自定义数据,通常设为null
      ​+ title网页标题,基本上没有被支持,一般设为空
      ​+ url 以当前域为基础增加一条历史记录,不可跨域设置
  • replaceState(data, title, url) 与pushState()基本相同,
    不同之处在于replaceState(),只是替换当前url,不会增加/减少历史记录。
  • onpopstate事件,当前进或后退时则触发
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--
历史相关api
history
history.back()  去上一条历史
history.forward() 去下一条历史
history.go() 相对当前  跳多少条记录   正 前走  负 后退
-->
<!--
H5新增一些
history.pushState();
history.replaceState();
window.onpopstate = function(){}
实现网页中常见的开发模式   单页面应用程序  single page application  SPA
什么单页面应用程序:在一个页面上实现网站的大部分功能
实现的方案:1:哈希 hash (路由)  2: 历史追加   特点:改变地址栏是不会跳转的
-->
<!--
ajax渲染
优点:性能更好,提高用户体验
缺点:不利于seo,搜索引擎收录的网页源码

解决方案:同时会去更改地址栏 (地址栏在服务端一定有对应的页面)
-->
<button class="btn1">追加历史</button>
<button class="btn2">替换当前历史</button>
<script>
    document.querySelector('.btn1').onclick = function () {
        /*1.存数据  null*/
        /*2.存标题  null*/
        /*3.追叫的历史记录的地址*/
        history.pushState(null,null,'test.html');
    }
    document.querySelector('.btn2').onclick = function () {
        /*1.存数据  null*/
        /*2.存标题  null*/
        /*3.替换的历史记录的地址*/
        history.replaceState(null,null,'test.html');
    }

    window.onpopstate = function(){
        /*监听历史切换事件*/
        /*当前地址 没有包括域名*/
        console.log(location.pathname);
    }
</script>
</body>
</html>
离线应用

HTML5中我们可以轻松的构建一个离线(无网络状态)应用,只需要创建一个cache manifest文件。

  • 优势

    • 1、可配置需要缓存的资源
    • 2、网络无连接应用仍可用
    • 3、本地读取缓存资源,提升访问速度,增强用户体验
    • 4、减少请求,缓解服务器负担
  • 缓存清单

    • 一个普通文本文件,其中列出了浏览器应缓存以供离线访问的资源,推荐使用.appcache为后缀名
    • 例如我们创建了一个名为demo.appcache的文件,然后在需要应用缓存在页面的根元素(html)添加属性manifest=“demo.appcache”,路径要保证正确。
  • manifest文件格式

    • 1、顶行写CACHE MANIFEST
    • 2、CACHE: 换行 指定我们需要缓存的静态资源,如.css、image、js等
    • 3、NETWORK: 换行 指定需要在线访问的资源,可使用通配符
    • 4、FALLBACK: 换行 当被缓存的文件找不到时的备用资源
  • 其它

    • 1、CACHE: 可以省略,这种情况下将需要缓存的资源写在CACHE MANIFEST
    • 2、可以指定多个CACHE: NETWORK: FALLBACK:,无顺序限制
    • 3、#表示注释,只有当demo.appcache文件内容发生改变时或者手动清除缓存后,才会重新缓存。
    • 4、chrome 可以通过chrome://appcache-internals/工具和离线(offline)模式来调试管理应用缓存
CACHE MANIFEST

CACHE:

#此部分写需要缓存的资源 (#是注释的意思)

./images/img1.jpg
./images/img2.jpg
./images/img3.jpg
./images/img4.jpg


NETWORK:

#此部分要写需要有网络才可访问的资源,无网络刚不访问

./js/main.js

*

FALLBACK:

#当访问不到某个资源的情况下,自动由另一个资源替换

./css/online.css ./css/offline.css

./online.html ./offline.html


文件读取

HTML5新增内建对象,可以读取本地文件内容。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>文件读取</title>
</head>
<body>
	<input type="file" class="file" multiple>
	<!--<select name="" id="">
		<option value=""></option>
	</select>-->
	<img src="" alt="" id="img">
	<script>
		/*获取到了文件表单元素*/
		var file = document.querySelector('.file');
		/*选择文件后触发*/
		file.onchange = function () {
			/*初始化了一个文件读取对象*/
			var reader = new FileReader();
			/*读取文件数据  this.files[0] 文件表单元素选择的第一个文件 */
			reader.readAsDataURL(this.files[0]);
			/*读取的过程就相当于 加载过程 */
			/*读取完毕  预览 */
			reader.onload = function () {
			    /*读取完毕 base64位数据  表示图片*/
			    console.log(this.result);
				document.querySelector('#img').src = this.result;

			}
		}
	</script>
</body>
</html>
网络状态
  • 我们可以通过window.onLine来检测,用户当前的网络状况,返回一个布尔值
    • window.online用户网络连接时被调用
    • window.offline用户网络断开时被调用
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>onLine</title>
	<style>
		body {
			padding: 0;
			margin: 0;
			background-color: #F7F7F7;
		}

		p {
			width: 200px;
			height: 40px;
			text-align: center;
			line-height: 40px;
			margin: 100px auto;
			color: #FFF;
			font-size: 24px;
			background-color: #000;
			display: none;
		}
	</style>
</head>
<body>
	<p class="tips"></p>
	<p>事件绑定方法</p>
	<script src="jquery.min.js"></script>
	<script>
		// 通过window.navigator.onLine可以返回当前的网络状态
		alert(window.navigator.onLine);

		window.addEventListener('online', function () {
			//alert('online');
			$('.tips').text('网络已连接').fadeIn(500).delay(1000).fadeOut();
		});

		window.addEventListener('offline', function () {
			//alert('offline');
			$('.tips').text('网络已断开').fadeIn(500).delay(1000).fadeOut();
		});
	</script>
</body>
</html>
border-image
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 400px;
            height: 150px;
            border: 20px solid #ccc;
            margin-bottom: 30px;
        }

        .box:first-child{
            /*border-image: url("images/border01.jpg") 167/20px round;*/
            /*1.在内容变化的容器可以使用,边框自动填充*/
            /*2.用法:*/
            /*2.1 图片资源*/
            border-image-source: url("images/border01.jpg");
            /*2.2 切割的尺寸 默认的单位px 而且不能使用小数*/
            /*2.2.1 切割的位置距离对应的边的距离  切了四刀   4个切割的尺寸*/
            border-image-slice: 167;/*167 167 167 167*/
            /*2.3 边框的宽度*/
            border-image-width: 20px;
            /*2.4 平铺的方式  三种平铺方式 round stretch repeat*/
            /*round 环绕 完整的自适应(等比缩放)平铺在边框内*/
            /*stretch 拉伸 拉伸显示在边框内容 变形的*/
            /*repeat 平铺 从边框的中间向两侧平铺 自适应平铺但是不是完整的*/
            border-image-repeat: round;

        }
        .box:nth-child(2){
            border-image: url("images/border01.jpg") 167/20px stretch;
        }
        .box:last-child{
            border-image: url("images/border01.jpg") 167/20px repeat;
        }


    </style>
</head>
<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</body>
</html>

拖拽

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>拖拽</title>
	<style>
		body {
			padding: 0;
			margin: 0;
			background-color: #F7F7F7;
			position: relative;
		}

		.box {
			width: 150px;
			height: 150px;
			background-color: yellow;
			position: absolute;
			top: 100px;
			left: 50px;
		}

		.container {
			width: 300px;
			height: 300px;
			background-color: green;
			position: absolute;
			top: 100px;
			left: 50%;
			margin-left: -150px;
		}
	</style>
</head>
<body>
	<div class="box" draggable="true"></div>
	<div class="container"></div>

	<script>
		var box = document.querySelector('.box');
		var container = document.querySelector('.container');

		// 整个拖拽都会执行
		box.addEventListener('drag', function (e) {
			console.log('drag');
		});

        // 拖拽的点离开当前盒子
		box.addEventListener('dragleave', function () {
			console.log('dragleave');
		});

		// 拖拽开始
		box.addEventListener('dragstart', function () {
			this.style.backgroundColor = 'red';
			console.log('dragstart')
		});

		// 拖拽结束
		box.addEventListener('dragend', function (ev) {
			this.style.backgroundColor = '';
			console.log('dragend');
		});


		//在目标元素上移动
		container.addEventListener('dragover', function (e) {
			this.style.backgroundColor = 'yellow';
            console.log('目标dragover');
			e.preventDefault();
		});

		//在目标元素松开
		container.addEventListener('drop', function (e) {
			this.style.backgroundColor = 'black';
			console.log('目标drop');
			e.preventDefault();
		});
        //在目标元素离开
        container.addEventListener('dragleave', function (e) {
            this.style.backgroundColor = '';
            console.log('目标dragleave');
            e.preventDefault();
        });
	</script>
</body>
</html>
发布了296 篇原创文章 · 获赞 562 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/tichimi3375/article/details/82837711