0
点赞
收藏
分享

微信扫一扫

JS具体实例(一)

fbd4ffd0717b 2022-02-08 阅读 69

实例

一、统计某个字符出现的次数并输出

var str = 'baobfabobodabfodao';
var index = str.indexOf('o');
var num = 0;
while (index != -1) {
    console.log(index);
    num++;
    index = str.indexOf('o', index + 1);
}
console.log('o出现的次数是:' + num);

结果如下:
在这里插入图片描述

二、统计字符串中出现的次数

let str = 'baobfabobodabfodao';
let num = str.split("").reduce((pre, cur) => {
    if (cur in pre) {
        pre[cur]++;
    } else {
        pre[cur] = 1;
    }
    return pre
}, {})
console.log('次数', num);

① 这里的split('' '')指的是,把一串字符串改为数组形式,然后用括号内的方式隔开
② reduce()方法具体:

let 结果数值变量 = 原数组.reduce((用于临时接收结果的新变量,用于索引的变量) => {
	......
	循环方法体
	......
},结果数值变量的初始值也可以不写)

三、点击关闭某部分

var foot = document.querySelector('.footer');
var img = foot.querySelector('img');
var meau = foot.querySelector('.meau');

img.onclick = () => {
    meau.style.display = 'none';
}

四、多精灵图一次性设置

1、精灵图的排列一定是有规律的

eg.(这里的精灵图例子位置是间隔44)

// 精灵图一次性设置(循环)
var lis = document.querySelector('li');
for (var i = 0; i < lis.clientHeight; i++) {
    // 让 索引号 乘以 规律间隔 ,就是每一个li的背景y坐标 index就是我们的y坐标
    var index = i * 44;
    lis[i].style.backgroundPosition = '0 -' + index + 'px';
}

五、全选

在这里插入图片描述

var cbAll = document.getElementById('cbAll');
var tbs = document.getElementById('tb').getElementsByTagName('input');

cbAll.onclick = () => {
    console.log(cbAll.checked);
    for (var i = 0; i < tbs.length; i++) {
        tbs[i].checked = cbAll.checked;
    }
}
for (var i = 0; i < tbs.length; i++) {
    tbs[i].onclick = () => {
        var flag = true;
        for (var i = 0; i < tbs.length; i++) {
            if (!tbs[i].checked) {
                flag = false;
            }
        }
        cbAll.checked = flag;
    }
}

六、tab栏切换案例

框架:
在这里插入图片描述
实际样式图:
在这里插入图片描述

window.onload = () => {
	var tab_list = document.querySelector('.tab_list');
	var lis = tab_list.querySelectorAll('li');
	var items = document.querySelectorAll('.item');
	
	for (let i = 0; i < lis.length; i++) {
	    lis[i].setAttribute('index', i);
	    lis[i].onclick = () => {
	        for (let i = 0; i < lis.length; i++) {
	            lis[i].className = '';
	        }
	        lis[i].className = 'current';
	        var index = lis[i].getAttribute('index');
	        for (let i = 0; i < lis.length; i++) {
	            items[i].style.display = 'none';
	        }
	        items[index].style.display = 'block';
	    }
	}
}

 

七、使js代码在确保页面加载完成后再进行

window.onload = () => {
	这里写 js 操作代码
}

八、下拉菜单显示与隐藏

<style>
    * {
        margin: 0;
        padding: 0;
    }

    li {
        list-style: none;
    }

    a {
        text-decoration: none;
        color: black;
    }

    .nav>li {
        float: left;
        position: relative;
        margin-left: 1px;
        margin-right: 1px;
    }

    .nav li {
        width: 100px;
        height: 50px;

        text-align: center;
        line-height: 50px;
    }

    .nav>li>a div {
        width: 100px;
        height: 50px;
        border-bottom: 1px solid black;
    }

    .nav>li>a div:hover {
        background-color: #ccc;
        color: orange;
    }

    .nav ul {
        display: none;
        position: absolute;
        top: 50px;
        left: -1px;
        width: 100%;
        border-left: 1px solid yellow;
        border-right: 1px solid yellow;
    }

    .nav ul li {
        border-bottom: 1px solid yellow;
    }

    .nav ul li a:hover {
        background-color: #FFF5DA;
    }
</style>

<body>
    <ul class="nav">
        <li>
            <a href="#">
                <div>微博</div>
            </a>
            <ul>
                <li>
                    <a href="#">私信</a>
                </li>
                <li>
                    <a href="#">评论</a>
                </li>
                <li>
                    <a href="#">@我</a>
                </li>
            </ul>
        </li>
        
        上面的<li>*3
        
    </ul>

    <script>
        window.onload = () => {
            var nav = document.querySelector('.nav');
            var lis = nav.children;
            for (let i = 0; i < lis.length; i++) {
                lis[i].onmouseover = () => {
                    lis[i].children[1].style.display = 'block';
                }
                lis[i].onmouseout = () => {
                    lis[i].children[1].style.display = 'none';
                }
            }
        }
    </script>
</body>

九、动态生成表格

(直接写数据生成表格最后删除)

<style>
    table {
        width: 500px;
        margin: 100px auto;
        border-collapse: collapse;
        text-align: center;
    }

    td,
    th {
        border: 1px solid #333;
    }

    thead tr {
        height: 40px;
        background-color: #ccc;
    }
</style>

<body>
    <table>
        <thead>
            <tr>
                <th>姓名</th>
                <th>科目</th>
                <th>成绩</th>
                <th>操作</th>
            </tr>
        </thead>

        <tbody>
        </tbody>
    </table>
    
    <script>
        window.onload = () => {
            var datas = [{
                name: '郑楷',
                subject: 'Java',
                score: 90,
            }, {
                name: '黄科然',
                subject: 'HTML',
                score: 100,
            }, {
                name: '不知道',
                subject: 'vue',
                score: 80,
            }];
            var tbody = document.querySelector('tbody');
            for (let i = 0; i < datas.length; i++) {
                let tr = document.createElement('tr');
                tbody.appendChild(tr);
                for (let k in datas[i]) {
                    let td = document.createElement('td');
                    td.innerHTML = datas[i][k];
                    tr.appendChild(td);
                }
                let td = document.createElement('td');
                td.innerHTML = '<a href = "javascript:;">删除</a>';
                tr.appendChild(td);
            }
            var as = document.querySelectorAll('a');
            for (let i = 0; i < as.length; i++) {
                as[i].onclick = () => {
                    tbody.removeChild(as[i].parentNode.parentNode);
                }
            }
        }
    </script>
</body>

结果如下:
在这里插入图片描述

十、图片跟随鼠标移动

<script>
    window.onload = () => {
        var img = document.querySelector('img');
        document.addEventListener('mousemove', function (e) {
        	//把鼠标为位置传递给系统
            let x = e.pageX;
            let y = e.pageY;
            //把位置变为图片的额位置,这里注意要加上 px 后缀
            //img.width/height/2 是让图片居中
            img.style.left = (x - (img.width / 2)) + 'px';
            img.style.top = (y - (img.height / 2)) + 'px';
        })
    }
</script>

十一、按下键盘S键,搜索框自动获得焦点

十二、输入内容的时候,在上方显示大字

十三、倒计时

<style>
        div {
            text-align: center;
            margin-top: 270px;
            font-size: 50px;

        }

        span {
            display: inline-block;
            margin-right: 10px;
            width: 100px;
            height: 100px;
            color: white;
            font-size: 40px;
            text-align: center;
            line-height: 100px;
            background-color: rgb(44, 43, 43);
        }
</style>

<body>
    <div>
        <span class="day">0</span><span class="hour">1</span>小时
        <span class="minute">2</span><span class="second">3</span></div>

    <script>
        var day = document.querySelector('.day');
        var hour = document.querySelector('.hour');
        var minute = document.querySelector('.minute');
        var second = document.querySelector('.second');
        var inputTime = +new Date('2022-1-1 00:00:00');

        countDown();
        setInterval(countDown, 1000);

        function countDown(Time) {
            let nowTime = +new Date();
            let times = (inputTime - nowTime) / 1000;

            var d = parseInt(times / 60 / 60 / 24);  //计算天数
            d = d < 10 ? '0' + d : d;
            day.innerHTML = d;

            var h = parseInt(times / 60 / 60 % 24);  //计算小时数
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h;

            var m = parseInt(times / 60 % 60);  //计算分钟数
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;

            var s = parseInt(times % 60);  //计算秒数
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
    </script>
</body>

十四、发送验证码(其中的计时禁用按键功能)

编程思路如下:
在这里插入图片描述

<div>
    手机号码:<input type="number"> &nbsp <button>发送</button>
</div>
<script>
    var btn = document.querySelector('button');
    var x = 3;
    btn.addEventListener('click', () => {
        btn.disabled = true;  //点击后先禁用按钮
        let time = setInterval(() => {
            if (x >= 0) {  //使其到0停止
                btn.innerHTML = '还剩下' + x-- + '秒'  //动态变化内部内容,形成计时效果
            } else {
                clearInterval(time);  //清除定时器
                btn.disabled = false;  //接触禁止
                btn.innerHTML = '发送';  //复原内部文字
                x = 3;  //复原计时器回到数字初始
            }
        }, 1000);
    })
</script>

十五、5秒钟后跳转页面

<body>
    <div>
    </div>
    <script>
        var div = document.querySelector('div');
        var x = 3;
        let time = setInterval(() => {
            if (x >= 0) {  //使其计时到0停止
                div.innerHTML = '您将在' + x-- + '秒后跳转到首页';
            } else {
                location.href = 'http://www.baidu.com';
            }
        }, 1000);
    </script>
</body>

十六、实时获得鼠标在局部盒子中的坐标

window.onload = () => {
    var box = document.querySelector('.box');
    box.addEventListener('mousemove', function (e) {
        let x = e.pageX - box.offsetLeft;
        let y = e.pageY - box.offsetTop;
        box.innerHTML = '鼠标在盒子里的X坐标:' + x + '<br>鼠标在盒子里的Y坐标:' + y;
    })
}

十七、鼠标拖拽小窗口

三个过程:
1、 鼠标按下
    ① 获得鼠标在盒子内的坐标
2、 鼠标移动 (要写在按下事件里面,否则会独立触发)
    ① 鼠标在页面中的坐标,减去,鼠标在盒子内的坐标**(由于鼠标拖拽过程中,坐标恒定),等于盒子新的坐标值(原理是盒子的坐标值本身就是以盒子外的 left 值和 top 值决定的)**
② 需要给这个事件加个名字,方便后面解除的 removeEventListener 可以用上。
3、鼠标松开
    ① 解除事件,使用 removeEventListener 事件

div.addEventListener('mousedown', (e) => {
    let x = e.pageX - box.offsetLeft;
    let y = e.pageY - box.offsetTop;
    // 因为是需要鼠标按下之后,才可以触发移动事件,所以写在里面
    div.addEventListener('mousemove', move)
    function move(e) {
        box.style.left = e.pageX - x + 'px';
        box.style.top = e.pageY - y + 'px';
    }
    div.addEventListener('mouseup', (e) => {
        div.removeEventListener('mousemove', move)
    })
})

十八、放大镜效果

三个过程:
1、鼠标经过图片区域,遮挡层和显示区盒子显示,离开隐藏这两个盒子
    ① 要有 mouseover 和 mouseout 鼠标经过和移出这两个事件
2、遮挡层跟随鼠标移动
    ① 获得鼠标在盒子内的坐标(鼠标坐标 - 盒子坐标)
    ② 左右各减去遮挡层的一半,使其跟随中心移动
    ③ 通过 if-else-if 算法,加上限制防止遮挡层超出盒子
(可以用 坐标 或者 移动距离 为参照数据,最好使用移动距离,计算量少,使服务器运行更顺畅
3、移动遮挡层,显示区盒子跟随移动功能
    ① 根据遮挡层在图片上移动的距离 等比例让显示区的图片跟着移动
    ② 注意显示区里面的图片需要定位,否则无法移动
    ③ 显示区图片的移动是跟遮挡层反方向的

<style>
    * {
        margin: 0;
        padding: 0;
    }

    .box {
        height: 400px;
    }

    .pic {
        position: relative;
        width: 250px;
        height: 250px;
        left: 40%;
        margin-left: -125px;
        margin-top: 100px;
    }

    .mask {
        display: none;
        position: absolute;
        width: 100px;
        height: 100px;
        background-color: yellow;
        z-index: 999;
        opacity: .6;
        cursor: move;
    }

    .pic img {
        width: 250px;
        height: 250px;
    }

    .see {
        display: none;
        position: absolute;
        width: 200px;
        height: 200px;
        left: 100%;
        top: 0px;
        z-index: 9999;
        border: #ebebeb solid 1px;
        box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);
        /* 超出的部分自动隐藏 */
        overflow: hidden;
    }

    .see img {
        position: absolute;
        top: 0;
        left: 0;
        width: 400px;
        height: 400px;
    }
</style>

<body>
    <div class="box">
        <div class="pic">
            <div class="mask"></div>
            <img src="images/2.jpg" alt="">
            <div class="see">
                <img src="images/2.jpg" alt="" class="seeImg">
            </div>
        </div>
    </div>

    <script>
        window.onload = () => {
            var pic = document.querySelector('.pic');
            var mask = document.querySelector('.mask');
            var see = document.querySelector('.see');
            var seeImg = document.querySelector('.seeImg');

            pic.addEventListener('mouseover', (e) => {
                mask.style.display = 'block';
                see.style.display = 'block';
            })
            pic.addEventListener('mouseout', (e) => {
                mask.style.display = 'none';
                see.style.display = 'none';
            })
            pic.addEventListener('mousemove', (e) => {
                let x = e.pageX - pic.offsetLeft;
                let y = e.pageY - pic.offsetTop;

                let maskX = x - mask.offsetWidth / 2;
                let maskY = y - mask.offsetHeight / 2;

                //最大移动距离
                let maskMaxX = pic.offsetWidth - mask.offsetWidth;
                let maskMaxY = pic.offsetHeight - mask.offsetHeight;

                if (maskX <= 0) {
                    maskX = 0;
                } else if (maskX >= maskMaxX) {
                    maskX = maskMaxX;
                }
                if (maskY <= 0) {
                    maskY = 0;
                } else if (maskY >= maskMaxY) {
                    maskY = maskMaxY;
                }
                mask.style.left = maskX + 'px';
                mask.style.top = maskY + 'px';

                //显示区图片移动
                //显示区的移动距离 = 遮挡层移动距离 * 显示区最大移动距离 / 遮挡层的最大移动距离
                //显示区最大移动距离
                let imgMaxX = seeImg.offsetWidth - see.offsetWidth;
                let imgMaxY = seeImg.offsetHeight - see.offsetHeight;

                //同比例移动距离
                let seeX = maskX * imgMaxX / maskMaxX;
                let seeY = maskY * imgMaxY / maskMaxY;

                seeImg.style.left = -seeX + 'px';
                seeImg.style.top = -seeY + 'px';
            })
        }
    </script>
</body>

十九、仿侧边栏滚动动态效果

效果:侧边栏先在下面随着页面滚动,当侧边栏到界面顶部时,固定不动,并在一定位置的时候,出现“回到顶部”的按钮
    ① 侧边栏原先是绝对定位
    ② 当页面滚动到一定位置,侧边栏改为固定定位
    ③ 页面继续滚动,会让“返回顶部”显示出来
    ④ 使用空链接,做到点击“返回顶部”就弹回顶部的效果

<body>
    <div class="slider-bar">
        <!-- 空标签自动弹回顶部 -->
        <span class="goback"><a href="#">返回顶部</a></span>
    </div>
    <div class="header base">头部区域</div>
    <div class="banner base">导航栏区域</div>
    <div class="main base">主体部分</div>
    <div class="footer base">底栏信息</div>

    <script>
        window.onload = () => {
            var sliderBar = document.querySelector('.slider-bar');
            var banner = document.querySelector('.banner');
            var main = document.querySelector('.main');
            var goBack = document.querySelector('.goback');

            let sliderBarTop = sliderBar.offsetTop; //计算侧边栏最开始到页面顶部的距离
            let mainTop = main.offsetTop;
            let sliderBarBet = sliderBar.offsetTop - mainTop; //计算侧边栏开始固定的位置距离(这里用主体部分参照物)


            document.addEventListener('scroll', () => {
                // sliderBar.innerHTML = window.pageYOffset;
                if (window.pageYOffset >= mainTop) {
                    sliderBar.style.position = 'fixed';
                    sliderBar.style.top = sliderBarBet + 'px';
                    goBack.style.display = 'block';
                } else {
                    sliderBar.style.position = 'absolute';
                    sliderBar.style.top = sliderBarTop + 'px';
                    goBack.style.display = 'none';
                }
            })
        }
    </script>
</body>

二十、网页轮播图

1、鼠标经过轮播图模块,左右按钮显示,离开隐藏左右按钮

2、点击右侧按钮一次,图片往左播放一张,以此类推,左侧按钮同理。

3、图片播放的同时,下面小圆圈模块跟随一起变化。

4、点击小圆圈,可以播放相应图片。

5、鼠标不经过轮播图,轮播图也会自动播放图片。

6、鼠标经过,轮播图模块,自动播放停止。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="index.css">
    <script src="../../animate.js"></script>
    <script src="index.js"></script>
</head>

<body>
    <div class="w">
        <div class="main">
            <div class="focus fl">
                <!-- 左按钮 -->
                <a href="javascript:;" class="arrow-l">
                    &lt;
                </a>
                <!-- 右按钮 -->
                <a href="javascript:;" class="arrow-r">
                    &gt;
                </a>
                <!-- 滚动区域 -->
                <ul>
                    <li>
                        <a href="#"><img src="../images/10.jpg" alt=""></a>
                    </li>
                    <li>
                        <a href="#"><img src="../images/29.jpg" alt=""></a>
                    </li>
                    <li>
                        <a href="#"><img src="../images/32.jpg" alt=""></a>
                    </li>
                    <li>
                        <a href="#"><img src="../images/49.jpg" alt=""></a>
                    </li>
                </ul>
                <ol class="circle">
                </ol>
            </div>
        </div>
    </div>

</body>

</html>
* {
    margin: 0;
    padding: 0;
}

a {
    text-decoration: none;
}

li {
    list-style: none;
}

img {
    width: 720px;
    height: 455px;
}

.main {
    width: 980px;
    height: 455px;
    margin-left: 219px;
    margin-top: 10px;
    
}

.focus {
    position: relative;
    width: 720px;
    height: 455px;
    background-color: purple;
    overflow: hidden;
}

.focus ul {
    position:absolute;
    top: 0;
    left: 0;
    width: 600%;
}

.focus ul li {
    float: left;
}

.arrow-l,
.arrow-r {
    display: none;
    position: absolute;
    top: 50%;
    margin-top: -20px;
    width: 24px;
    height: 40px;
    background: rgba(0, 0, 0, .3);
    text-align: center;
    line-height: 40px;
    color: #fff;
    font-family: 'icomoon';
    font-size: 18px;
    z-index: 2;
}

.arrow-r {
    right: 0;
}

.circle {
    position: absolute;
    bottom: 10px;
    left: 50px;
}

.circle li {
    float: left;
    width: 8px;
    height: 8px;
    border: 2px solid rgba(225, 255, 225, 0.5);
    margin: 0px 3px;
    border-radius: 50%;
    /* 鼠标经过有小手 */
    cursor: pointer;
}

.current {
    background-color: #fff;
}
window.onload = () => {
    // alert('123');
    var focus = document.querySelector('.focus')
    var arrowL = document.querySelector('.arrow-l');
    var arrowR = document.querySelector('.arrow-r');
    var ul = focus.querySelector('ul');
    var ol = focus.querySelector('.circle');

    var num = 0;//索引号

    //一张图片的宽度
    var focusWidth = focus.offsetWidth;

    // 鼠标经过左右按钮显示和隐藏
    focus.addEventListener('mouseenter', () => {
        arrowL.style.display = 'block';
        arrowR.style.display = 'block';
        clearInterval(timer);
    })
    focus.addEventListener('mouseleave', () => {
        arrowL.style.display = 'none';
        arrowR.style.display = 'none';
        timer = setInterval(() => {
            arrowR.click();
        }, 2000);
    })

    // 动态生成小圆圈
    for (let i = 0; i < ul.children.length; i++) {
        //计算有多少个ul,等于有多少个图片
        //按个数创建小li
        let li = document.createElement('li');
        //获取这个li后,自定义给它加上一个索引号(属性值的索引号)
        li.setAttribute('index', i);
        //插入
        ol.appendChild(li);
        //加入排他算法
        li.addEventListener('mouseover', () => {
            for (let i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            }
            //给 ol 中的经过的 li 加上 current 样式
            li.className = 'current';

            //获取点击的小li的索引号
            let index = li.getAttribute('index');
            num = li.getAttribute('index');
            //移动的算法的就是 索引号*图片 的宽度,等于需要移动的距离
            animate(ul, -(index * focusWidth));
        })
    }
    //首先默认给第一个小圆圈附加样式
    ol.children[0].className = 'current';

    //克隆第一张图片到最后面
    var firstImg = ul.children[0].cloneNode(true);
    ul.appendChild(firstImg);



    //右按钮点击
    arrowR.addEventListener('click', () => {
        //先判断当前是否是克隆图,是的话直接跳转到第一张,实现无缝连接
        if (num == ul.children.length - 1) {
            ul.style.left = 0;
            num = 0;
        }
        num++;//因为索引号排序问题,在右边的图片必定是更大的数
        animate(ul, -num * focusWidth);

        //调用小圆圈样式方法
        circle(num);
    })

    //左按钮点击(与右按钮同理)
    arrowL.addEventListener('click', () => {
        if (num == 0) {
            ul.style.right = 0;
            num = ul.children.length - 1;
        }
        num--;
        animate(ul, -num * focusWidth);
        circle(num);
    })

    //自动播放(定时器原理)
    var timer = setInterval(() => {
        arrowR.click();
    }, 2000);



    //方法区
    //小圆圈判断加样式方法
    function circle(e) {
        //先清空所有小圆圈的样式
        for (let i = 0; i < ol.children.length; i++) {
            ol.children[i].className = "";
        }
        //判断是不是克隆图,是的话直接给第一个小圆圈加样式
        if (e == ul.children.length - 1) {
            ol.children[0].className = 'current';
        } else {
            //否则正常加样式
            ol.children[e].className = 'current';
        }
    }
}

二十一、

举报

相关推荐

0 条评论