JavaScript实际开发案例

Pink老师整理

 

全选反选案例

		<ul>
			<li>
				<input type="checkbox">
			</li>
			<li>
				<input type="checkbox">
			</li>
			<li>
				<input type="checkbox">
			</li>
			<li>
				<input type="checkbox">
			</li>
			<li>
				<input type="checkbox">
			</li>
		</ul>
		<script>
			var checkboxs = document.querySelector('ul').getElementsByTagName('input');
			//全选反选
			checkboxs[0].onclick = function() {
				for (var i = 1; i < checkboxs.length; i++) {
					checkboxs[i].checked = this.checked;
				}
			}
			//当有下面的复选框都被选中时,全选才会被选中
			for (var i = 1; i < checkboxs.length; i++) {
				checkboxs[i].onclick = function(){
					checkboxs[0].checked = true;
					for (var j = 1; j < checkboxs.length; j++) {
						if(checkboxs[i].checked == false){
							checkboxs[0].checked = false;
							break;
						}
					}
				}
			}
		</script>

 

tag栏切换

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			div {
				width: 600px;
				height: 600px;
				margin: 0 auto;
			}

			ul {
				margin: 0;
				padding: 0;
				list-style: none;
			}

			.nav li {
				display: inline-block;
				width: 100px;
				height: 50px;
				line-height: 50px;
				text-align: center;
				cursor: pointer;
			}

			.content li {
				width: 600px;
				height: 200px;
				display: none;
			}

			.selected {
				background-color: red;
				color: #fff;
			}
		</style>
	</head>
	<body>
		<div>
			<ul class="nav">
				<li class="selected">按钮1</li>
				<li>按钮2</li>
				<li>按钮3</li>
				<li>按钮4</li>
				<li>按钮5</li>
			</ul>
			<ul class="content">
				<li style="background-color: black; display: block;"></li>
				<li style="background-color: yellow;"></li>
				<li style="background-color: grey;"></li>
				<li style="background-color: aqua;"></li>
				<li style="background-color: cornflowerblue;"></li>
			</ul>
		</div>

		<script>
			var nav_li = document.querySelector('.nav').querySelectorAll('li');
			var content_li = document.querySelector('.content').querySelectorAll('li');
			for (var i = 0; i < nav_li.length; i++) {
				nav_li[i].setAttribute('index', i);
				nav_li[i].onclick = function() {
					var index = this.getAttribute('index');
					for (var i = 0; i < nav_li.length; i++) {
						nav_li[i].className = '';
						content_li[i].style.display = 'none';
					}
					this.className = 'selected';
					content_li[index].style.display = 'block';
				}
			}
		</script>
	</body>
</html>

 

下拉菜单

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        li {
            list-style-type: none;
        }
        
        a {
            text-decoration: none;
            font-size: 14px;
        }
        
        .nav {
            margin: 100px;
        }
        
        .nav>li {
            position: relative;
            float: left;
            width: 80px;
            height: 41px;
            text-align: center;
        }
        
        .nav li a {
            display: block;
            width: 100%;
            height: 100%;
            line-height: 41px;
            color: #333;
        }
        
        .nav>li>a:hover {
            background-color: #eee;
        }
        
        .nav ul {
            display: none;
            position: absolute;
            top: 41px;
            left: 0;
            width: 100%;
            border-left: 1px solid #FECC5B;
            border-right: 1px solid #FECC5B;
        }
        
        .nav ul li {
            border-bottom: 1px solid #FECC5B;
        }
        
        .nav ul li a:hover {
            background-color: #FFF5DA;
        }
    </style>
</head>

<body>
    <ul class="nav">
        <li>
            <a href="#">微博</a>
            <ul>
                <li>
                    <a href="">私信</a>
                </li>
                <li>
                    <a href="">评论</a>
                </li>
                <li>
                    <a href="">@我</a>
                </li>
            </ul>
        </li>
        <li>
            <a href="#">微博</a>
            <ul>
                <li>
                    <a href="">私信</a>
                </li>
                <li>
                    <a href="">评论</a>
                </li>
                <li>
                    <a href="">@我</a>
                </li>
            </ul>
        </li>
        <li>
            <a href="#">微博</a>
            <ul>
                <li>
                    <a href="">私信</a>
                </li>
                <li>
                    <a href="">评论</a>
                </li>
                <li>
                    <a href="">@我</a>
                </li>
            </ul>
        </li>
        <li>
            <a href="#">微博</a>
            <ul>
                <li>
                    <a href="">私信</a>
                </li>
                <li>
                    <a href="">评论</a>
                </li>
                <li>
                    <a href="">@我</a>
                </li>
            </ul>
        </li>
    </ul>
    <script>
        // 1. 获取元素
        var nav = document.querySelector('.nav');
        var lis = nav.children; // 得到4个小li
        // 2.循环注册事件
        for (var i = 0; i < lis.length; i++) {
            lis[i].onmouseover = function() {
                this.children[1].style.display = 'block';
            }
            lis[i].onmouseout = function() {
                this.children[1].style.display = 'none';
            }
        }
    </script>
</body>

</html>

 

简单版发布留言板案例

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        body {
            padding: 100px;
        }
        
        textarea {
            width: 200px;
            height: 100px;
            border: 1px solid pink;
            outline: none;
            resize: none;
        }
        
        ul {
            margin-top: 50px;
			list-style: none;
        }
        
        li {
            width: 300px;
            padding: 5px;
            background-color: rgb(245, 209, 243);
            color: red;
            font-size: 14px;
            margin: 15px 0;
        }
    </style>
</head>

<body>
    <textarea name="" id=""></textarea>
    <button>发布</button>
    <ul>

    </ul>
    <script>
        // 1. 获取元素
        var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        // 2. 注册事件
        btn.onclick = function() {
            if (text.value == '') {
                alert('您没有输入内容');
                return false;
            } else {
                // console.log(text.value);
                // (1) 创建元素
                var li = document.createElement('li');
                // 先有li 才能赋值
                li.innerHTML = text.value;
                // (2) 添加元素
                // ul.appendChild(li);
                ul.insertBefore(li, ul.children[0]);
            }
        }
    </script>
</body>

</html>

 

删除留言案例

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        body {
            padding: 100px;
        }
        
        textarea {
            width: 200px;
            height: 100px;
            border: 1px solid pink;
            outline: none;
            resize: none;
        }
        
        ul {
            margin-top: 50px;
        }
        
        li {
            width: 300px;
            padding: 5px;
            background-color: rgb(245, 209, 243);
            color: red;
            font-size: 14px;
            margin: 15px 0;
        }
        
        li a {
            float: right;
        }
    </style>
</head>

<body>
    <textarea name="" id=""></textarea>
    <button>发布</button>
    <ul>

    </ul>
    <script>
        // 1. 获取元素
        var btn = document.querySelector('button');
        var text = document.querySelector('textarea');
        var ul = document.querySelector('ul');
        // 2. 注册事件
        btn.onclick = function() {
            if (text.value == '') {
                alert('您没有输入内容');
                return false;
            } else {
                // console.log(text.value);
                // (1) 创建元素
                var li = document.createElement('li');
                // 先有li 才能赋值
                li.innerHTML = text.value + "<a href='javascript:;'>删除</a>";
                // (2) 添加元素
                // ul.appendChild(li);
                ul.insertBefore(li, ul.children[0]);
                // (3) 删除元素 删除的是当前链接的li  它的父亲
                var as = document.querySelectorAll('a');
                for (var i = 0; i < as.length; i++) {
                    as[i].onclick = function() {
                        // node.removeChild(child); 删除的是 li 当前a所在的li  this.parentNode;
                        ul.removeChild(this.parentNode);
                    }
                }
            }
        }
    </script>
</body>

</html>

 

动态生成表格案例

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

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

	<body>
		<table cellspacing="0">
			<thead>
				<tr>
					<th>姓名</th>
					<th>科目</th>
					<th>成绩</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>

			</tbody>
		</table>
		<script>
			// 1.先去准备好学生的数据
			var datas = [{
				name: '魏璎珞',
				subject: 'JavaScript',
				score: 100
			}, {
				name: '弘历',
				subject: 'JavaScript',
				score: 98
			}, {
				name: '傅恒',
				subject: 'JavaScript',
				score: 99
			}, {
				name: '明玉',
				subject: 'JavaScript',
				score: 88
			}, {
				name: '大猪蹄子',
				subject: 'JavaScript',
				score: 0
			}];
			// 2. 往tbody 里面创建行: 有几个人(通过数组的长度)我们就创建几行
			var tbody = document.querySelector('tbody');
			for (var i = 0; i < datas.length; i++) { // 外面的for循环管行 tr
				// 1. 创建 tr行
				var tr = document.createElement('tr');
				tbody.appendChild(tr);
				// 2. 行里面创建单元格(跟数据有关系的3个单元格) td 单元格的数量取决于每个对象里面的属性个数  for循环遍历对象 datas[i]
				for (var k in datas[i]) { // 里面的for循环管列 td
					// 创建单元格 
					var td = document.createElement('td');
					// 把对象里面的属性值 datas[i][k] 给 td  
					// console.log(datas[i][k]);
					td.innerHTML = datas[i][k];
					tr.appendChild(td);
				}
				// 3. 创建有删除2个字的单元格 
				var td = document.createElement('td');
				td.innerHTML = '<a href="javascript:;">删除 </a>';
				tr.appendChild(td);

			}
			// 4. 删除操作 开始 
			var as = document.querySelectorAll('a');
			for (var i = 0; i < as.length; i++) {
				as[i].onclick = function() {
					// 点击a 删除 当前a 所在的行(链接的爸爸的爸爸)  node.removeChild(child)  
					tbody.removeChild(this.parentNode.parentNode)
				}
			}
			// for(var k in obj) {
			//     k 得到的是属性名
			//     obj[k] 得到是属性值
			// }
		</script>
	</body>

</html>

 

图片跟随鼠标移动案例

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        img {
            position: absolute;
            top: 2px;
        }
    </style>
</head>

<body>
    <img src="img/angel.gif" alt="">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function(e) {
            // 1. mousemove只要我们鼠标移动1px 就会触发这个事件
            // console.log(1);
            // 2.核心原理: 每次鼠标移动,我们都会获得最新的鼠标坐标, 把这个x和y坐标做为图片的top和left 值就可以移动图片
            var x = e.pageX;
            var y = e.pageY;
            console.log('x坐标是' + x, 'y坐标是' + y);
            //3 . 千万不要忘记给left 和top 添加px 单位
            pic.style.left = x - 50 + 'px';
            pic.style.top = y - 40 + 'px';


        });
    </script>
</body>

</html>

 

模拟京东按键获得搜索框焦点

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

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

<body>
    <input type="text">
    <script>
        // 核心思路: 检测用户是否按下了s 键,如果按下s 键,就把光标定位到搜索框里面
        // 使用键盘事件对象里面的keyCode 判断用户按下的是否是s键
        // 搜索框获得焦点: 使用 js 里面的 focus() 方法
        var search = document.querySelector('input');
        document.addEventListener('keyup', function(e) {
            // console.log(e.keyCode);
            if (e.keyCode === 83) {
                search.focus();
            }
        })
    </script>
</body>

</html>

 

模拟京东快递单号查询

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .search {
            position: relative;
            width: 178px;
            margin: 100px;
        }
        
        .con {
            display: none;
            position: absolute;
            top: -40px;
            width: 171px;
            border: 1px solid rgba(0, 0, 0, .2);
            box-shadow: 0 2px 4px rgba(0, 0, 0, .2);
            padding: 5px 0;
            font-size: 18px;
            line-height: 20px;
            color: #333;
        }
        
        .con::before {
            content: '';
            width: 0;
            height: 0;
            position: absolute;
            top: 28px;
            left: 18px;
            border: 8px solid #000;
            border-style: solid dashed dashed;
            border-color: #fff transparent transparent;
        }
    </style>
</head>

<body>
    <div class="search">
        <div class="con">123</div>
        <input type="text" placeholder="请输入您的快递单号" class="jd">
    </div>
    <script>
        // 快递单号输入内容时, 上面的大号字体盒子(con)显示(这里面的字号更大)
        // 表单检测用户输入: 给表单添加键盘事件
        // 同时把快递单号里面的值(value)获取过来赋值给 con盒子(innerText)做为内容
        // 如果快递单号里面内容为空,则隐藏大号字体盒子(con)盒子
        var con = document.querySelector('.con');
        var jd_input = document.querySelector('.jd');
        jd_input.addEventListener('keyup', function(e) {
                // console.log('输入内容啦');
                if (e.keyCode == 32 || this.value == '') {
                    con.style.display = 'none';
                } else {
                    con.style.display = 'block';
                    con.innerText = this.value;
                }
            })
            // 当我们失去焦点,就隐藏这个con盒子
        jd_input.addEventListener('blur', function() {
                con.style.display = 'none';
            })
            // 当我们获得焦点,就显示这个con盒子
        jd_input.addEventListener('focus', function() {
            if (this.value !== '') {
                con.style.display = 'block';
            }
        })
    </script>
</body>

 

倒计时

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            margin: 200px;
        }
        
        span {
            display: inline-block;
            width: 40px;
            height: 40px;
            background-color: #333;
            font-size: 20px;
            color: #fff;
            text-align: center;
            line-height: 40px;
        }
    </style>
</head>

<body>
    <div>
        <span class="hour">1</span>
        <span class="minute">2</span>
        <span class="second">3</span>
    </div>
    <script>
        // 1. 获取元素 
        var hour = document.querySelector('.hour'); // 小时的黑色盒子
        var minute = document.querySelector('.minute'); // 分钟的黑色盒子
        var second = document.querySelector('.second'); // 秒数的黑色盒子
        var inputTime = +new Date('2019-5-1 18:00:00'); // 返回的是用户输入时间总的毫秒数
        countDown(); // 我们先调用一次这个函数,防止第一次刷新页面有空白 
        // 2. 开启定时器
        setInterval(countDown, 1000);

        function countDown() {
            var nowTime = +new Date(); // 返回的是当前时间总的毫秒数
            var times = (inputTime - nowTime) / 1000; // times是剩余时间总的秒数 
            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>

</html

 

发送短信延迟

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

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

	<body>
		<input type="text">
		<button>发送</button>
		<script>
			var input = document.querySelector('input');
			var button = document.querySelector('button');
			var s = 60;
			button.addEventListener('click', function() {
				this.disabled = true;
				a();
				var timer = setInterval(a, 1000);

				function a() {
					if (s != 1) {
						s--;
						button.innerHTML = s + '秒后重新发送';
					} else {
						clearInterval(timer);
						button.disabled = false;
						button.innerHTML = '发送';
						s = 60;
					}
				}
			});
		</script>
	</body>

</html>

 

页面找不到,5秒后跳回案例

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

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

	<body>
		<div></div>
		<script>
			var div = document.querySelector('div');
			var s = 5;
			function timer() {
				if (s != 0) {
					div.innerHTML = '页面没找到,' + s + '秒之后跳回百度'
					s--;
				} else {
					clearInterval(timer);
					location.href = 'https://www.baidu.com/';
					s = 5;
				}
			}
			timer();
			setInterval(timer, 1000);
		</script>
	</body>

</html

 

获取URL参数数据

login.html

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

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

<body>
    <form action="index.html" method="get">
        用户名: <input type="text" name="uname">
        <input type="submit" value="登录">
    </form>
</body>

</html>

index.html

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

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

<body>
    <div></div>
    <script>
        console.log(location.search); // ?uname=andy
        // 1.先去掉?  substr('起始的位置',截取几个字符);
        var params = location.search.substr(1); // uname=andy
        console.log(params);
        // 2. 利用=把字符串分割为数组 split('=');
        var arr = params.split('=');
        console.log(arr); // ["uname", "ANDY"]
        var div = document.querySelector('div');
        // 3.把数据写入div中
        div.innerHTML = arr[1] + '欢迎您';
    </script>
</body>

</html>

 

获取鼠标在盒子内的坐标案例

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background-color: pink;
            margin: 200px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        // 我们在盒子内点击, 想要得到鼠标距离盒子左右的距离。
        // 首先得到鼠标在页面中的坐标( e.pageX, e.pageY)
        // 其次得到盒子在页面中的距离(box.offsetLeft, box.offsetTop)
        // 用鼠标距离页面的坐标减去盒子在页面中的距离, 得到 鼠标在盒子内的坐标
        var box = document.querySelector('.box');
        box.addEventListener('mousemove', function(e) {
            // console.log(e.pageX);
            // console.log(e.pageY);
            // console.log(box.offsetLeft);
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            this.innerHTML = 'x坐标是' + x + ' y坐标是' + y;
        })
    </script>
</body>

</html>

 

模拟框拖拽

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .login-header {
            width: 100%;
            text-align: center;
            height: 30px;
            font-size: 24px;
            line-height: 30px;
        }
        
        ul,
        li,
        ol,
        dl,
        dt,
        dd,
        div,
        p,
        span,
        h1,
        h2,
        h3,
        h4,
        h5,
        h6,
        a {
            padding: 0px;
            margin: 0px;
        }
        
        .login {
            display: none;
            width: 512px;
            height: 280px;
            position: fixed;
            border: #ebebeb solid 1px;
            left: 50%;
            top: 50%;
            background: #ffffff;
            box-shadow: 0px 0px 20px #ddd;
            z-index: 9999;
            transform: translate(-50%, -50%);
        }
        
        .login-title {
            width: 100%;
            margin: 10px 0px 0px 0px;
            text-align: center;
            line-height: 40px;
            height: 40px;
            font-size: 18px;
            position: relative;
            cursor: move;
        }
        
        .login-input-content {
            margin-top: 20px;
        }
        
        .login-button {
            width: 50%;
            margin: 30px auto 0px auto;
            line-height: 40px;
            font-size: 14px;
            border: #ebebeb 1px solid;
            text-align: center;
        }
        
        .login-bg {
            display: none;
            width: 100%;
            height: 100%;
            position: fixed;
            top: 0px;
            left: 0px;
            background: rgba(0, 0, 0, .3);
        }
        
        a {
            text-decoration: none;
            color: #000000;
        }
        
        .login-button a {
            display: block;
        }
        
        .login-input input.list-input {
            float: left;
            line-height: 35px;
            height: 35px;
            width: 350px;
            border: #ebebeb 1px solid;
            text-indent: 5px;
        }
        
        .login-input {
            overflow: hidden;
            margin: 0px 0px 20px 0px;
        }
        
        .login-input label {
            float: left;
            width: 90px;
            padding-right: 10px;
            text-align: right;
            line-height: 35px;
            height: 35px;
            font-size: 14px;
        }
        
        .login-title span {
            position: absolute;
            font-size: 12px;
            right: -20px;
            top: -30px;
            background: #ffffff;
            border: #ebebeb solid 1px;
            width: 40px;
            height: 40px;
            border-radius: 20px;
        }
    </style>
</head>

<body>
    <div class="login-header"><a id="link" href="javascript:;">点击,弹出登录框</a></div>
    <div id="login" class="login">
        <div id="title" class="login-title">登录会员
            <span><a id="closeBtn" href="javascript:void(0);" class="close-login">关闭</a></span>
        </div>
        <div class="login-input-content">
            <div class="login-input">
                <label>用户名:</label>
                <input type="text" placeholder="请输入用户名" name="info[username]" id="username" class="list-input">
            </div>
            <div class="login-input">
                <label>登录密码:</label>
                <input type="password" placeholder="请输入登录密码" name="info[password]" id="password" class="list-input">
            </div>
        </div>
        <div id="loginBtn" class="login-button"><a href="javascript:void(0);" id="login-button-submit">登录会员</a></div>
    </div>
    <!-- 遮盖层 -->
    <div id="bg" class="login-bg"></div>
    <script>
        // 1. 获取元素
        var login = document.querySelector('.login');
        var mask = document.querySelector('.login-bg');
        var link = document.querySelector('#link');
        var closeBtn = document.querySelector('#closeBtn');
        var title = document.querySelector('#title');
        // 2. 点击弹出层这个链接 link  让mask 和login 显示出来
        link.addEventListener('click', function() {
                mask.style.display = 'block';
                login.style.display = 'block';
            })
            // 3. 点击 closeBtn 就隐藏 mask 和 login 
        closeBtn.addEventListener('click', function() {
                mask.style.display = 'none';
                login.style.display = 'none';
            })
            // 4. 开始拖拽
            // (1) 当我们鼠标按下, 就获得鼠标在盒子内的坐标
        title.addEventListener('mousedown', function(e) {
            var x = e.pageX - login.offsetLeft;
            var y = e.pageY - login.offsetTop;
            // (2) 鼠标移动的时候,把鼠标在页面中的坐标,减去 鼠标在盒子内的坐标就是模态框的left和top值
            document.addEventListener('mousemove', move)

            function move(e) {
                login.style.left = e.pageX - x + 'px';
                login.style.top = e.pageY - y + 'px';
            }
            // (3) 鼠标弹起,就让鼠标移动事件移除
            document.addEventListener('mouseup', function() {
                document.removeEventListener('mousemove', move);
            })
        })
    </script>
</body>

</html>

 

伪京东放大镜

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

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>Document</title>
		<style>
			.de_container {
				margin-top: 20px;
			}

			.crumb_wrap {
				height: 25px;
			}

			.crumb_wrap a {
				margin-right: 10px;
			}

			.preview_wrap {
				width: 400px;
				height: 590px;
			}

			.preview_img {
				position: relative;
				height: 398px;
				border: 1px solid #ccc;
			}

			.mask {
				display: none;
				position: absolute;
				top: 0;
				left: 0;
				width: 300px;
				height: 300px;
				background: #FEDE4F;
				opacity: .5;
				border: 1px solid #ccc;
				cursor: move;
			}

			.big {
				display: block;
				position: absolute;
				left: 410px;
				top: 0;
				width: 500px;
				height: 500px;
				background-color: pink;
				z-index: 999;
				border: 1px solid #ccc;
				overflow: hidden;
			}

			.big img {
				position: absolute;
				top: 0;
				left: 0;
			}
		</style>

		<script>
			window.addEventListener('load', function() {
				var preview_img = document.querySelector('.preview_img');
				var mask = document.querySelector('.mask');
				var big = document.querySelector('.big');
				// 1. 当我们鼠标经过 preview_img 就显示和隐藏 mask 遮挡层 和 big 大盒子
				preview_img.addEventListener('mouseover', function() {
					mask.style.display = 'block';
					big.style.display = 'block';
				})
				preview_img.addEventListener('mouseout', function() {
					mask.style.display = 'none';
					big.style.display = 'none';
				})
				// 2. 鼠标移动的时候,让黄色的盒子跟着鼠标来走
				preview_img.addEventListener('mousemove', function(e) {
					// (1). 先计算出鼠标在盒子内的坐标
					var x = e.pageX - this.offsetLeft;
					var y = e.pageY - this.offsetTop;
					// console.log(x, y);
					// (2) 减去盒子高度 300的一半 是 150 就是我们mask 的最终 left 和top值了
					// (3) 我们mask 移动的距离
					var maskX = x - mask.offsetWidth / 2;
					var maskY = y - mask.offsetHeight / 2;
					// (4) 如果x 坐标小于了0 就让他停在0 的位置
					// 遮挡层的最大移动距离
					var maskMax = preview_img.offsetWidth - mask.offsetWidth;
					if (maskX <= 0) {
						maskX = 0;
					} else if (maskX >= maskMax) {
						maskX = maskMax;
					}
					if (maskY <= 0) {
						maskY = 0;
					} else if (maskY >= maskMax) {
						maskY = maskMax;
					}
					mask.style.left = maskX + 'px';
					mask.style.top = maskY + 'px';
					// 3. 大图片的移动距离 = 遮挡层移动距离 * 大图片最大移动距离 / 遮挡层的最大移动距离
					// 大图
					var bigIMg = document.querySelector('.bigImg');
					// 大图片最大移动距离
					var bigMax = bigIMg.offsetWidth - big.offsetWidth;
					// 大图片的移动距离 X Y
					var bigX = maskX * bigMax / maskMax;
					var bigY = maskY * bigMax / maskMax;
					bigIMg.style.left = -bigX + 'px';
					bigIMg.style.top = -bigY + 'px';

				})

			})
		</script>
	</head>

	<body>

		<div class="de_container w">
			<div class="preview_wrap">
				<div class="preview_img">
					<img src="img/s3.png">
					<div class="mask"></div>
					<div class="big">
						<img src="img/big.jpg" class="bigImg">
					</div>
				</div>
			</div>
		</div>

	</body>

</html>

 

仿淘宝固定侧边栏

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        //1. 获取元素
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // banner.offestTop 就是被卷去头部的大小 一定要写到滚动的外面
        var bannerTop = banner.offsetTop
            // 当我们侧边栏固定定位之后应该变化的数值
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        // 获取main 主体元素
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 2. 页面滚动事件 scroll
        document.addEventListener('scroll', function() {
            // console.log(11);
            // window.pageYOffset 页面被卷去的头部
            // console.log(window.pageYOffset);
            // 3 .当我们页面被卷去的头部大于等于了 172 此时 侧边栏就要改为固定定位
            if (window.pageYOffset >= bannerTop) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = '300px';
            }
            // 4. 当我们页面滚动到main盒子,就显示 goback模块
            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }

        })
    </script>
</body>

</html>

注意:

  • 需要用到页面滚动事件 scroll  因为是页面滚动,所以事件源是 document
  • 页面被卷去的头部:可以通过window.pageYOffset 获得  如果是被卷去的左侧 window.pageXOffset
  • 元素被卷去的头部是 element.scrollTop  , 如果是页面被卷去的头部 则是 window.pageYOffset

需要注意的是,页面被卷去的头部,有兼容性问题,因此被卷去的头部通常有如下几种写法: 

  1. 声明了 DTD,使用 document.documentElement.scrollTop 
  2. 未声明 DTD,使用  document.body.scrollTop 
  3. 新方法 window.pageYOffset 和 window.pageXOffset,IE9 开始支持 
 function getScroll() { 
    return { 
      left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft||0, 
      top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0 
    }; 
 }  
使用的时候  getScroll().left

 

仿淘宝返回首页

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主体部分</div>
    <script>
        //1. 获取元素
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // banner.offestTop 就是被卷去头部的大小 一定要写到滚动的外面
        var bannerTop = banner.offsetTop
            // 当我们侧边栏固定定位之后应该变化的数值
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        // 获取main 主体元素
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 2. 页面滚动事件 scroll
        document.addEventListener('scroll', function() {
                // console.log(11);
                // window.pageYOffset 页面被卷去的头部
                // console.log(window.pageYOffset);
                // 3 .当我们页面被卷去的头部大于等于了 172 此时 侧边栏就要改为固定定位
                if (window.pageYOffset >= bannerTop) {
                    sliderbar.style.position = 'fixed';
                    sliderbar.style.top = sliderbarTop + 'px';
                } else {
                    sliderbar.style.position = 'absolute';
                    sliderbar.style.top = '300px';
                }
                // 4. 当我们页面滚动到main盒子,就显示 goback模块
                if (window.pageYOffset >= mainTop) {
                    goBack.style.display = 'block';
                } else {
                    goBack.style.display = 'none';
                }

            })
            // 3. 当我们点击了返回顶部模块,就让窗口滚动的页面的最上方
        goBack.addEventListener('click', function() {
            // 里面的x和y 不跟单位的 直接写数字即可
            // window.scroll(0, 0);
            // 因为是窗口滚动 所以对象是window
            animate(window, 0);
        });
        // 动画函数
        function animate(obj, target, callback) {
            // console.log(callback);  callback = function() {}  调用的时候 callback()

            // 先清除以前的定时器,只保留当前的一个定时器执行
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                // 步长值写到定时器的里面
                // 把我们步长值改为整数 不要出现小数的问题
                // var step = Math.ceil((target - obj.offsetLeft) / 10);
                var step = (target - window.pageYOffset) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (window.pageYOffset == target) {
                    // 停止动画 本质是停止定时器
                    clearInterval(obj.timer);
                    // 回调函数写到定时器结束里面
                    // if (callback) {
                    //     // 调用函数
                    //     callback();
                    // }
                    callback && callback();
                }
                // 把每次加1 这个步长值改为一个慢慢变小的值  步长公式:(目标值 - 现在的位置) / 10
                // obj.style.left = window.pageYOffset + step + 'px';
                window.scroll(0, window.pageYOffset + step);
            }, 15);
        }
    </script>
</body>

</html>

 

筋斗云案例

<!DOCTYPE html>
<html>

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

			ul {
				list-style: none;
			}

			body {
				background-color: black;
			}

			.c-nav {
				width: 900px;
				height: 42px;
				background: #fff url(img/rss.png) no-repeat right center;
				margin: 100px auto;
				border-radius: 5px;
				position: relative;
			}

			.c-nav ul {
				position: absolute;
			}

			.c-nav li {
				float: left;
				width: 83px;
				text-align: center;
				line-height: 42px;
			}

			.c-nav li a {
				color: #333;
				text-decoration: none;
				display: inline-block;
				height: 42px;
			}

			.c-nav li a:hover {
				color: white;
			}

			.c-nav li.current a {
				color: #0dff1d;
			}

			.cloud {
				position: absolute;
				left: 0;
				top: 0;
				width: 83px;
				height: 42px;
				background: url(img/cloud.gif) no-repeat;
			}
		</style>
		<script>
			window.addEventListener('load', function() {
				// 1. 获取元素
				var cloud = document.querySelector('.cloud');
				var c_nav = document.querySelector('.c-nav');
				var lis = c_nav.querySelectorAll('li');
				// 2. 给所有的小li绑定事件 
				// 这个current 做为筋斗云的起始位置
				var current = 0;
				for (var i = 0; i < lis.length; i++) {
					// (1) 鼠标经过把当前小li 的位置做为目标值
					lis[i].addEventListener('mouseenter', function() {
						animate(cloud, this.offsetLeft);
					});
					// (2) 鼠标离开就回到起始的位置 
					lis[i].addEventListener('mouseleave', function() {
						animate(cloud, current);
					});
					// (3) 当我们鼠标点击,就把当前位置做为目标值
					lis[i].addEventListener('click', function() {
						current = this.offsetLeft;
					});
				}

				function animate(obj, target, callback) {
					// console.log(callback);  callback = function() {}  调用的时候 callback()

					// 先清除以前的定时器,只保留当前的一个定时器执行
					clearInterval(obj.timer);
					obj.timer = setInterval(function() {
						// 步长值写到定时器的里面
						// 把我们步长值改为整数 不要出现小数的问题
						// var step = Math.ceil((target - obj.offsetLeft) / 10);
						var step = (target - obj.offsetLeft) / 10;
						step = step > 0 ? Math.ceil(step) : Math.floor(step);
						if (obj.offsetLeft == target) {
							// 停止动画 本质是停止定时器
							clearInterval(obj.timer);
							// 回调函数写到定时器结束里面
							// if (callback) {
							//     // 调用函数
							//     callback();
							// }
							callback && callback();
						}
						// 把每次加1 这个步长值改为一个慢慢变小的值  步长公式:(目标值 - 现在的位置) / 10
						obj.style.left = obj.offsetLeft + step + 'px';

					}, 15);
				}
			})
		</script>
	</head>

	<body>
		<div id="c_nav" class="c-nav">
			<span class="cloud"></span>
			<ul>
				<li class="current"><a href="#">首页新闻</a></li>
				<li><a href="#">师资力量</a></li>
				<li><a href="#">活动策划</a></li>
				<li><a href="#">企业文化</a></li>
				<li><a href="#">招聘信息</a></li>
				<li><a href="#">公司简介</a></li>
				<li><a href="#">我是佩奇</a></li>
				<li><a href="#">啥是佩奇</a></li>
			</ul>
		</div>
	</body>

</html>

图片:

 

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值