WEB前端第三十五课——事件绑定应用案例

1.放大镜案例

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片放大镜</title>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .div1{
        width: 405px;
        height: 270px;
        background-image: url("Images/drink.jpg");
        background-size: contain;
        position: relative;
        float: left;
    }
    .div2{
        width: 81px;
        height: 54px;
        background-color: rgba(211,135,113,0.3);
        position: absolute;
        display: none;
    }
    .div3{
        width: 405px;
        height: 270px;
        float: left;
        overflow: hidden;
        position: relative;
        display: none;
    }
    .div3 img{
        position: absolute;
    }
    .changeBtn{
        outline: none;
        position: absolute;
        left: 0;
        top: 270px;
    }
</style>
</head>
<body>
    <div class="div1" >
        <div class="div2"></div>
    </div>
    <button class="changeBtn">切换图片</button>
    <div class="div3">
        <img src="Images/drink.jpg" alt="">
    </div>
<script>
    var lessenPic=document.querySelector('.div1');
    var magnifier=document.querySelector('.div2');
    var largePic=document.querySelector('img');
    var enlargement=document.querySelector('.div3');
    var changeBtn=document.querySelector('.changeBtn');
    lessenPic.onmousemove=function (eve) {
        var e=eve||window.event;
        var moveLeft=e.clientX-40.5;
        var moveTop=e.clientY-27;
        switch (true){
            case moveLeft<0:moveLeft=0;
                break;
            case moveLeft>324:moveLeft=324;
                break;
            case moveLeft>=0&&moveLeft<=324:magnifier.style.left=moveLeft+'px';
                break;
        }
        switch (true){
            case moveTop<0:moveTop=0;
                break;
            case moveTop>216:moveTop=216;
                break;
            case moveTop>=0&&moveTop<=216:magnifier.style.top=moveTop+'px';
                break;
        }
        magnifier.style.display='block';
        enlargement.style.display='block';
        largePic.style.left=(-3.75)*moveLeft+'px';
        largePic.style.top=(-3.75)*moveTop+'px';
    };
    lessenPic.onmouseleave=function () {
        magnifier.style.display='none';
        enlargement.style.display='none';
    };
    changeBtn.onclick=function () {
        lessenPic.style.backgroundImage='url("Images/stairs.jpg")';
        largePic.setAttribute('src','Images/stairs.jpg');
        largePic.setAttribute('width','1620px');
        largePic.setAttribute('height','1080px');
    }
</script>
</body>
</html>

2.三级联动案例

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三级联动</title>
    <style>
        select{ width: 168px; height: 30px; outline: none;}
        option{ text-align: center; }
        span{ margin-left: 30px; }
    </style>
</head>
<body>
    <span>省:</span>
    <select name="province" id="province">
        <option value="makeChoice">--------选择省份--------</option>
    </select>
    <span>市:</span>
    <select name="city" id="city"></select>
    <span>区/县:</span>
    <select name="county" id="county"></select>
<script>
    var province=document.querySelector('#province')
    var city=document.querySelector('#city')
    var county=document.querySelector('#county')
    var provinceArr=["北京市","天津市","上海市","重庆市","河北省","四川省"];
    var cityArr=[
        ["东城区","西城区","崇文区","宣武区","朝阳区","丰台区","石景山区","海淀区","门头沟区","房山区","通州区","顺义区","昌平区","大兴区","怀柔区","平谷区","密云县","延庆县"],
        ["和平区","河东区","河西区","南开区","河北区","红桥区","塘沽区","汉沽区","大港区","东丽区","西青区","津南区","北辰区","武清区","宝坻区","蓟县","宁河县","静海县"],
        ["黄浦区","卢湾区","徐汇区","长宁区","静安区","普陀区","闸北区","虹口区","杨浦区","闵行区","宝山区","嘉定区","浦东新区","金山区","松江区","青浦区","南汇区","奉贤区","崇明县"],
        ["渝中区","大渡口区","江北区","沙坪坝区","九龙坡区","南岸区","北碚区","万盛区","双桥区","渝北区","巴南区","万州区","涪陵区","黔江区","长寿区","合川市","永川市","江津市","南川市","綦江县","潼南县","铜梁县","大足县","荣昌县","璧山县","垫江县","武隆县","丰都县","城口县","梁平县","开县","巫溪县","巫山县","奉节县","云阳县","忠县","石柱土家族自治县","彭水苗族土家族自治县","酉阳土家族苗族自治县","秀山土家族苗族自治县"],
        ["石家庄市","张家口市","承德市","秦皇岛市","唐山市","廊坊市","保定市","衡水市","沧州市","邢台市","邯郸市"],
        ["成都市","广元市","绵阳市","德阳市","南充市","广安市","遂宁市","内江市","乐山市","自贡市","泸州市","宜宾市","攀枝花市","巴中市","达州市","资阳市","眉山市","雅安市","阿坝州","甘孜州","凉山州"]
    ];
    var countyArr=[
        [],
        [],
        [],
        [],
        [
            ["长安区","桥东区","桥西区","新华区","裕华区","井陉矿区","辛集市","藁城市","晋州市","新乐市","鹿泉市","井陉县","微水镇","正定县","正定镇","栾城县","栾城镇","行唐县","龙州镇","灵寿县","灵寿镇","高邑县","高邑镇","深泽县","深泽镇","赞皇县","赞皇镇","无极县","无极镇","平山县","平山镇","元氏县","槐阳镇","赵县"],
            ["桥西区","桥东区","宣化区","下花园区","宣化县","张家口市宣化区","张北县","张北镇","康保县","康保镇","沽源县","平定堡镇","尚义县","南壕堑镇","蔚县","蔚州镇","阳原县","西城镇","怀安县","柴沟堡镇","万全县","孔家庄镇","怀来县","沙城镇","涿鹿县","涿鹿镇","赤城县","赤城镇","崇礼县"],
            ["双桥区","双滦区","鹰手营子矿区","承德县","下板城镇","兴隆县","兴隆镇","平泉县","平泉镇","滦平县","滦平镇","隆化县","隆化镇","丰宁满族自治县","大阁镇","宽城满族自治县","宽城镇","围场满族蒙古族自治县"]
        ],
        [
            ["青羊区","锦江区","金牛区","武侯区","成华区","龙泉驿区","青白江区","新都区","温江区","都江堰市","彭州市","邛崃市","崇州市","金堂县","赵镇","双流县","郫县","郫筒镇","大邑县","晋原镇","蒲江县","鹤山镇","新津县"],
            ["市中区","元坝区","朝天区","旺苍县","东河镇","青川县","乔庄镇","剑阁县","下寺镇","苍溪县"],
            ["涪城区","游仙区","江油市","三台县","潼川镇","盐亭县","云溪镇","安县","花荄镇","梓潼县","文昌镇","北川羌族自治县","曲山镇","平武县"]
        ]
    ];
    for (var i=0;i<provinceArr.length;i++){
        var provinceOption=new Option(provinceArr[i]);  //创建省份选项内容
        province.options.add(provinceOption);           //将创建的省份添加到容器
    }
    var provinceIndex=0;
    var cityIndex=0;

    province.onchange=function (eve) {                  //通过 onchange事件实现联动(一)
        var e=eve || window.event;
        provinceIndex=e.target.selectedIndex-1;         //通过“change”事件获取所选省份的Index
        console.log(provinceIndex);
        if (provinceIndex<0){                 //为了实现省份编号与城市数组下标对应,获取provinceIndex时进行了“-1”处理,(四)
            city.options.length=0;            //导致省份第一个选项编号等于-1,为避免获取城市数组时的 for循环报错,增加 if判断
            county.options.length=0;
        }else{
            city.options.length=0;  //在选择或切换省份选项时,需要对城市option进行一次清空,否则后续省份的城市会直接追加在一起(三)
            for (var j=0;j<cityArr[provinceIndex].length;j++){        //通过for循环按照省份编号获取对应的城市数组内容(二)
                var cityOption=new Option(cityArr[provinceIndex][j]);    //创建城市选项内容
                city.options.add(cityOption);                         //将创建的城市添加到容器
            }
            //在省份option触发 onchange事件时,城市option会根据获取的省份编号默认省份中的第一个城市,但区县option无法获取
            //城市的编号,所以此处不能使用 cityIndex,直接赋值[0]作为默认城市编号,将第一个市的区县添加到区县容器。
            county.options.length=0;
            if (provinceIndex<4){
                county.options.add(new Option(cityArr[provinceIndex][0]));
            }else{
                for (var k=0;k<countyArr[provinceIndex][0].length;k++){
                    var countyOption=new Option(countyArr[provinceIndex][0][k]);
                    county.options.add(countyOption);
                }
            }
        }
    };
    city.onchange=function () {
        cityIndex = event.target.selectedIndex;
        county.options.length = 0;
        if (provinceIndex<4){
            county.options.add(new Option(cityArr[provinceIndex][cityIndex]));
        }else{
            for (var m = 0; m < countyArr[provinceIndex][cityIndex].length; m++) {
                var countyOption = new Option(countyArr[provinceIndex][cityIndex][m]);
                county.options.add(countyOption);
            }
        }
    }
</script>
</body>
</html>

3.知识碎片

  ① select元素(对象)用于创建HTML中的下拉列表,一个<select>标签就代表一个下拉框

    通常 select需要与 option配合使用

    在js中,select元素的 option创建方式:var newOpt= new Option(' selectObject ');

        select元素添加 option的方式:selectOpts .options .add( newOpt );

        select元素清空 option的方式:selectOpts .options .length = 0;

        select内容改变时触发的事件:selectOpts .onchange = function(){ };

        select当前选中 option的序号:var index = selectOpts .selectedIndex;(序号从0开始)

  ② <option>标签用于定义包含在<select>、<optgroup>或<datalist>元素中的项

    在 js中,options 用于表示<select>元素中所有的<option>标签的一个“数组

      语法:var 变量名 = selectObject .options;

    options属性:.length表示options数组的长度,.selectedIndex 返回已选择的option的索引值

    Options方法:.options[index],通过指定索引检索对应元素

          .options. item(index),返回指定索引的元素

          .Options.add(' '),向options中添加指定数组元素

  ③ <datalist>标签要与 input配合使用,用于为 input输入框创建可选列表

    需要通过 <input>元素的 list属性绑定 datalist元素

    语法示例:

      <input  list="fruits"> 
      <datalist  id="fruits"> 
         <option value="apple"> 
          <option value="peach"> 
          <option value="purple"> 
      </datalist>

4.事件委托案例

  在 js中对获取的对象进行事件绑定,对于使用 js方法创建的相同对象,该事件无效

  针对此种场景,借助冒泡事件的特性,将事件绑定在父元素上,用于监听子元素的冒泡事件,并定位相应子元素  

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件委托</title>
</head>
<body>
<div>
    <ul>
        <li>liOne</li>
        <li>liTwo</li>
        <li>liThree</li>
    </ul>
    <button>增加li</button>
</div>
<script>
    var ul=document.querySelector('ul');
    var lis=document.querySelectorAll('li');
    for (var i=0;i<lis.length;i++){
        lis[i].onclick=function () {
            console.log(this.innerHTML);
        }
    }
    var btn=document.querySelector('button');
    btn.onclick=function () {
        var newLi=document.createElement('li');
        newLi.innerHTML='newLi';
        ul.appendChild(newLi);
    }
//    上述书写方式下,通过 js创建的 newLi元素无法调用 lis[i]绑定的 onclick事件
//    可以通过对 newLi再绑定一个与 lis[i]相同的 onclick事件解决,但会造成代码冗余
//    而使用<事件委托>的方式,可以很好的解决该问题,
//    即只需要在 li的父元素 ul上绑定一次onclick事件,书写方式如下:
    ul.onclick = function () {
        console.log(event.target.innerHTML);
    }
</script>
</body>
</html>

5.全选、反选案例  

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>勾选取消案例</title>
</head>
<body>
    <button class="chkAll">全选</button>
    <button class="cancelAll">取消</button>
    <button class="chkRev">反选</button>
    <div style="margin:10px 30px">
        <input type="checkbox">手机 <br>
        <input type="checkbox">手表 <br>
        <input type="checkbox">项链 <br>
        <input type="checkbox">外套 <br>
        <input type="checkbox">帽子 <br>
        <input type="checkbox">眼镜 <br>
        <input type="checkbox">手枪 <br>
    </div>
<script>
    var checkAll=document.querySelector('.chkAll');
    var cancelAll=document.querySelector('.cancelAll');
    var chkReverse=document.querySelector('.chkRev');
    var checkList=document.querySelectorAll('input');
    checkAll.onclick=function () {
        for (var i=0;i<checkList.length;i++){
            checkList[i].checked=true;
        }
    };
    cancelAll.onclick=function () {
        for (var i=0;i<checkList.length;i++){
            checkList[i].checked=false;
        }
    };
    chkReverse.onclick=function () {
        for (var i=0;i<checkList.length;i++){
            if (checkList[i].checked==false){
                checkList[i].checked=true;
            }else{
                checkList[i].checked=false;
            }
        }
    };
</script>
</body>
</html>

  

(0)

相关推荐