目录
IE:fromElement &W3C:relatedTarget
鼠标滚轮(mousewheel)和DOMMouseScroll,用于获取鼠标上下滚轮的距离。
JavaScript事件是由访问Web页面的用户引起的一系列操作,例如:用户点击。当用户执行某些操作的时候,再去执行一系列代码。
JavaScript有三种事件模型:内联模型、脚本模型和DOM2模型。
这种模型是最传统接单的一种处理事件的方法。在内联模型中,事件处理函数是HTML标签的一个属性,用于处理指定事件。虽然内联在早期使用较多,但它是和HTML混写的,并没有与HTML分离。
在HTML中把事件处理函数作为属性执行JS代码
//注意单双引号
//在HTML中把事件处理函数作为属性执行JS函数
//执行JS的函数
PS:函数不得放到window.onload里面,这样就看不见了。
由于内联模型违反了HTML与JavaScript代码层次分离的原则。为了解决这个问题,我们可以在JavaScript中处理事件。这种处理方式就是脚本模型。
var input = document.getElementsByTagName('input')[0]; //得到input对象
input.onclick = function () { //匿名函数执行
alert('Lee');
};
通过匿名函数,可以直接触发对应的代码。也可以通过指定的函数名赋值的方式来执行函数(赋值的函数名不要跟着括号)。
input.onclick = box;
JavaScript可以处理的事件类型为:鼠标事件、键盘事件、HTML事件。



所有的事件处理函数都会都有两个部分组成,on + 事件名称,例如click事件的事件处理函数就是:onclick。
click:当用户单击鼠标按钮。
input.onclick = function () {
alert('Lee');
};
dblclick:当用户双击主鼠标按钮时触发。
input.ondblclick = function () {
alert('Lee');
};
mousedown:当用户按下了鼠标还未弹起时触发。
input.onmousedown = function () {
alert('Lee');
};
mouseup:当用户释放鼠标按钮时触发。
input.onmouseup = function () {
alert('Lee');
};
mouseover:当鼠标移到某个元素上方时触发。 mouseenter
input.onmouseover = function () {
alert('Lee');
};
mouseout:当鼠标移出某个元素上方时触发。 mouseleave
input.onmouseout = function () {
alert('Lee');
};
mousemove:当鼠标指针在元素上移动时触发。
input.onmousemove = function () {
alert('Lee');
};
keydown:当用户按下键盘上任意键触发,如果按住不放,会重复触发。
document.onkeydown = function (e) {
alert('Lee');
};
keypress:当用户按下键盘上的字符键触发,如果按住不放,会重复触发。
document.onkeypress = function () {
alert('Lee');
};
keyup:当用户释放键盘上的键触发。
document.onkeyup = function () {
alert('Lee');
};
select:当用户选择文本框(input或textarea)中的一个或多个字符触发。
input.onselect = function () {
alert('Lee');
};
change:当文本框(input或textarea)内容改变且失去焦点后触发。
input.onchange = function () {
alert('Lee');
};
focus:当页面或者元素获得焦点时在window及相关元素上面触发。
input.onfocus = function () {
alert('Lee');
};
blur:当页面或元素失去焦点时在window及相关元素上触发。
input.onblur = function () {
alert('Lee');
};
submit:当用户点击提交按钮在
reset:当用户点击重置按钮在
resize:当窗口或框架的大小变化时在window或框架上触发。
window.onresize = function () {
alert('Lee');
};
scroll:当用户滚动带滚动条的元素时触发。
window.onscroll = function () {
alert('Lee');
};


问题一:一个事件处理函数触发两次事件
window.onload = function () { //第一组程序项目或第一个JS文件
alert('Lee');
};
window.onload = function () { /第二组程序项目或第二个JS文件
alert('Mr.Lee');
};
当两组程序或两个JS文件同时执行的时候,后面一个会把前面一个完全覆盖掉。导致前面的window.onload完全失效了。
--------事件由最开始的元素接收,然后逐级向上传播到最不具体的那个节点(文档)
--------事件由最最不具体的那个节点(文档)元素接收,然后逐级向下广播到最具体的那个元素
“DOM2级事件”定义了两个方法,用于添加事件和删除事件处理程序的操作:addEventListener()和removeEventListener()。所有DOM节点中都包含这两个方法,并且它们都接受3个参数;事件名、函数、冒泡或捕获的布尔值(true表示捕获,false表示冒泡)。
window.addEventListener('load', function () {
alert('Lee');
}, false);
window.addEventListener('load', function () {
alert('Mr.Lee');
}, false);
IE实现了与DOM中类似的两个方法:attachEvent()和detachEvent()。这两个方法接受相同的参数:事件名称和函数。
在使用这两组函数的时候,先把区别说一下:
1.IE不支持捕获,只支持冒泡;
2.IE中的this指向的是window而不是DOM对象。
3在传统事件上,IE是无法接受到event对象的,但使用了attachEvent()却可以,但有些区别。
window.attachEvent('onload', function () {
var box = document.getElementById('box');
box.attachEvent('onclick', toBlue);
});function toRed() {
var that = window.event.srcElement;
that.className = 'red';
that.detachEvent('onclick', toRed);
that.attachEvent('onclick', toBlue);
}function toBlue() {
var that = window.event.srcElement;
that.className = 'blue';
that.detachEvent('onclick', toBlue);
that.attachEvent('onclick', toRed);
}
- <body>
- <button id="btn">按钮button>
- body>
- <script>
- var oBtn = document.getElementById("btn");
- // oBtn.onclick = function () {
- // console.log(this);
- // }
- // oBtn.addEventListener("click", function () {
- // console.log(this);
- // });
-
- oBtn.attachEvent("onclick", function () {
- // console.log(this);//window
- // fun.call(oBtn,2,8);
- // fun.apply(oBtn,[2,8]);
- fun.bind(oBtn, [2, 8])();
- });
-
-
- function fun(a, b) {
- console.log(this);
- this.style.backgroundColor = "red";
- }
-
- script>
window.attachEvent('onload', function () {
var box = document.getElementById('box');
box.attachEvent('onclick', function () {
alert(this === window); //this指向的window
});
});
window.attachEvent('onload', function () {
var box = document.getElementById('box');
box.attachEvent('onclick', function () {
fn1.call(box); //把this直接call过去
});
});function fn1() {
alert(this.tagName);
}
在传统绑定上,IE是无法像W3C那样通过传参接受event对象,但如果使用了attachEvent()却可以。
box.onclick = function (evt) {
alert(evt); //
}
box.attachEvent('onclick', function (evt) {
alert(evt); //object
alert(evt.type); //click
});
function addEvent(obj, type, fn) { //添加事件兼容
if (obj.addEventListener) {
obj.addEventListener(type, fn);
} else if (obj.attachEvent) {
obj.attachEvent('on' + type, fn);
}
}function removeEvent(obj, type, fn) { //移除事件兼容
if (obj.removeEventListener) {
obj.removeEventListener(type, fn);
} else if (obj.detachEvent) {
obj.detachEvent('on' + type, fn);
}
}
function getTarget(evt) { //得到事件目标
if (evt.target) {
return evt.target;
} else if (window.event.srcElement) {
return window.event.srcElement;
}
}
box.onmouseover = function (evt) { / /鼠标移入box
alert(window.event.fromElement.tagName); //获取移入box最近的那个元素对象span
}box.onmouseout = function (evt) { //鼠标移入box
alert(window.event.toElement.tagName); //获取移入box最近的那个元素对象span
}relatedTarget 事件属性返回与事件的目标节点相关的节点。
对于 mouseover 事件来说,该属性是鼠标指针移到目标节点上时所离开的那个节点。
对于 mouseout 事件来说,该属性是离开目标时,鼠标指针进入的节点。
对于其他类型的事件来说,这个属性没有用。
有时我们需要阻止事件对象的默认行为,比如:一个超链接的默认行为就点击然后跳转到指定的页面。那么阻止默认行为就可以屏蔽跳转的这种操作,而实现自定义操作。
方法一:
link.onclick = function () {
alert('Lee');
return false; //直接给个假,就不会跳转了。
};方法二:
W3C:evt.preventDefault();
IE: evt.returnValue = false
returnValue是javascript中html的window对象的属性,目的是返回窗口值function prevDefault(evt) {
var e = evt || window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;//ie
}
};
- <body>
- <a href="http://www.baidu.com" id="link">超链接a>
- body>
- <script>
- var oA = document.getElementById("link");
- oA.onclick = function (ev) {
- var evt = ev || window.event;
- console.log('我要去百度了');
- // return false;
- // ev.preventDefault();//阻止默认行为
- // evt.returnValue = false;//ie8及以下版本
- if (evt.preventDefault) {
- evt.preventDefault();
- } else {
- evt.returnValue = false;//ie8及以下版本
- }
- }
- script>
思路:
1,把要拖放的元素变成可拖动的元素,加属性draggable=true(是否能拖动)
2,要拖动的元素要有事件 ondragstart,开始拖动(怎么拖动)
3,拖动后,要找目标放到哪,目标要有事件 ondragover(拖动到目标上方)
ondrop(鼠标松开放下)(拖动后放到哪)所用知识点:
1,属性:draggable
2,事件:ondragstart,ondragover,ondrop
3, ev.dataTransfer.setData(“Text”,元素id) //数据传递属性,以文本的形式存放起来
4,ev.dataTransfer.getData("Text")默认地,无法将数据/元素放置到其他元素中。如果需要设置允许放置,我们必须阻止对元素的默认处理方式。
- <style>
- .box {
- width: 300px;
- height: 300px;
- box-shadow: 0 0 0 2px #200;
- }
- style>
- head>
-
- <body>
- <div class="box" ondragover="over(event)" ondrop="drop(event)">div>
- <img src="./img/down-0.png" alt="" id="pic" draggable="true" ondragstart="start(event)">
- <div class="box" ondragover="over(event)" ondrop="drop(event)">div>
- body>
- <script>
- // 1, 把要拖放的元素变成可拖动的元素,加属性draggable = true(是否能拖动)
- // 2, 要拖动的元素要有事件 ondragstart,开始拖动(怎么拖动)
- // 3, 拖动后,要找目标放到哪,目标要有事件 ondragover(拖动到目标上方)
- // ondrop(鼠标松开放下)(拖动后放到哪)
-
- // var oImg = document.getElementById("pic");
- function start(ev) {
- console.log("开始拖动了");
- ev.dataTransfer.setData("text", ev.target.id);//把要拖动到元素的id存放起来
- }
-
- function over(ev) {
- ev.preventDefault();// 默认情况下,数据 / 元素不能放置到其他元素中。 如果要实现改功能,我们需要防止元素的默认处理方法。我们可以通过调用 event.preventDefault() 方法来实现 ondragover 事件。
- // console.log(ev);//dragEvent
- // ev.target.style.boxShadow = "0 0 0 2px #f00"
- }
-
- function drop(ev) {
- console.log(ev.target);
- // console.log(ev.dataTransfer.getData("text"));//把之前存进去的id值取出来
- var id = ev.dataTransfer.getData("text");
- ev.target.appendChild(document.getElementById(id));
- }
- script>
w3c的方法是e.stopPropagation(),IE则是使用e.cancelBubble = true
stopPropagation也是事件对象(Event)的一个方法,作用是阻止目标元素的冒泡事件,但是会不阻止默认行为
取消事件冒泡,在 IE 的事件机制中,触发事件会从子元素向父元素逐级上传,就是说,如果子元素触发了单击事件,那么也会触发父元素的单击事 件;event.cancelBubble=true;可以停止事件继续上传补充一点,IE的事件传递是从下到上的:
事件来源对象->上级对象->上上级对象->.....->body->document->window兼容写法
function cBuble(evt){
var e=window.event||evt;
if(e.stopPropagation){
e.stopPropagation();
}else{
e.cancelBubble=true;
}
}
- <body>
- <div class="father">
- 父元素div
- <p class="child">子元素pp>
- div>
- body>
- <script>
- var oFather = document.querySelector(".father");
- var oChild = document.querySelector(".child");
-
- oChild.onclick = function (ev) {
- var evt = ev || window.event;
- console.log("你点击的是子节点");
- // ev.stopPropagation();//w3c
- // evt.cancelBubble = true;//ie8
- if (evt.stopPropagation) {
- ev.stopPropagation();//w3c ie9及以上版本
- } else {
- evt.cancelBubble = true;//ie8
- }
- }
- oFather.onclick = function (ev) {
- // ev.stopPropagation()
- console.log("你点击的是父节点");
- }
- document.onclick = function () {
- console.log("你点击的是老宗主");
- }
-
- script>
判断滚轮向上或向下在浏览器中也要考虑兼容性,现在五大浏览器(IE、Opera、Safari、Firefox、Chrome)中Firefox 使用detail,其余四类使用wheelDelta;两者只在取值上不一致,代表含义一致,detail与wheelDelta只各取两个 值,detail只取±3,wheelDelta只取±120,其中正数表示为向上,负数表示向下。
addEvent(document, 'mousewheel', function (evt) { //非火狐
alert(getWD(evt));//往上滚动120,往下滚动-120
});
addEvent(document, 'DOMMouseScroll', function (evt) { //火狐
alert(getWD(evt));
});
function getWD(evt) {
var e = evt || window.event;
if (e.wheelDelta) {
return e.wheelDelta;
} else if (e.detail) {
return -e.detail * 40; //保持计算的统一
}
}
- <style>
- * {
- margin: 0;
- padding: 0;
- }
-
- .fullpage {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- }
-
- .fullpage .page {
- width: 100%;
- height: 100%;
- text-align: center;
- font-size: 30px;
- }
-
- .fullpage .page:nth-of-type(1) {
- background-color: #d12;
- }
-
- .fullpage .page:nth-of-type(2) {
- background-color: #1d2;
- }
-
- .fullpage .page:nth-of-type(3) {
- background-color: #12d;
- }
-
- .fullpage .page:nth-of-type(4) {
- background-color: #a5b;
- }
-
- .fullpage .page:nth-of-type(5) {
- background-color: #b51;
- }
-
- .fullpage .page:nth-of-type(6) {
- background-color: #6ba;
- }
-
- .list {
- position: fixed;
- top: 0;
- left: 0;
- display: flex;
- list-style: none;
- background-color: #000;
- opacity: .6;
- }
-
- .list li {
- width: 100px;
- height: 40px;
- text-align: center;
- line-height: 40px;
- z-index: 9999;
- color: #fff;
- cursor: pointer;
- }
- style>
- head>
-
- <body>
- <div class="fullpage">
- <div class="page">第1屏div>
- <div class="page">第2屏div>
- <div class="page">第3屏div>
- <div class="page">第4屏div>
- <div class="page">第5屏div>
- <div class="page">第6屏div>
- div>
- <ul class="list">
- <li style="background-color: red;">第一屏li>
- <li>第二屏li>
- <li>第三屏li>
- <li>第四屏li>
- <li>第五屏li>
- <li>第六屏li>
- ul>
- body>
- <script>
- window.onload = init;
- window.onresize = init;
- function init() {
- var fp = document.querySelector(".fullpage");
- var pages = document.querySelectorAll(".fullpage .page");
- var lis = document.querySelectorAll(".list li");
- var index = 0;//滚出的屏幕的数量 默认0
- var vh = document.documentElement.clientHeight;//获取浏览器可视区域的高度
- for (var i = 0; i < pages.length; i++) {
- pages[i].style.height = vh + "px";
- }
- //move()
- //非火狐
- document.addEventListener("mousewheel", throttle(move, 500));
- //火狐
- document.addEventListener("DOMMouseScroll", throttle(move, 500));
- for (let i = 0; i < lis.length; i++) {
- lis[i].onclick = function () {
- console.log(lis[i]);
- for (let j = 0; j < lis.length; j++) {
- lis[j].style.backgroundColor = "";
- }
- lis[i].style.backgroundColor = "red"
- fp.style.top = -i * vh + "px";
- fp.style.transition = "0.5s";
- index = i
- }
- }
-
- function move(ev) {
- if (getWD(ev) < 0) {//往下滚动
- // console.log("往下滚动");
- index++;
- if (index > pages.length - 1) {
- index = pages.length - 1;
- }
- }
- if (getWD(ev) > 0) {
- index--;
- if (index < 0) {
- index = 0
- }
- }
- for (let j = 0; j < lis.length; j++) {
- lis[j].style.backgroundColor = "";
- }
- lis[index].style.backgroundColor = "red";
- fp.style.top = -index * vh + "px";
- fp.style.transition = "0.5s";
- }
- }
-
-
-
-
-
- //判断滚动方向
- function getWD(ev) {
- var evt = ev || window.event;
- if (evt.wheelDelta) {
- return evt.wheelDelta;//非火狐
- } else if (evt.detail) {
- return -evt.detail * 40;
- }
- }
- //节流
- function throttle(fn, mustRun = 500) {
- const timer = null;
- let previous = null;
- return function () {
- const now = new Date();
- const context = this;
- const args = arguments;
- if (!previous) {
- previous = now;
- }
- const remaining = now - previous;
- if (mustRun && remaining >= mustRun) {
- fn.apply(context, args);
- previous = now;
- }
- }
- }
- script>
- <body>
- <div class="title">
- <div class="shishen"><a href="#" class="active" name="pic_tit">绘世花鸟卷a>div>
- <div class="shishen"><a href="#" name="pic_tit">因幡辉夜姬a> div>
- <div class="shishen"><a href="#" name="pic_tit">铃彦姬a>div>
- <div class="shishen"><a href="#" name="pic_tit">神堕八岐大蛇a>div>
- <div class="shishen"><a href="#" name="pic_tit">大夜摩天阎王a>div>
- <div class="shishen"><a href="#" name="pic_tit">心狩鬼女红叶a>div>
- <div class="shishen"><a href="#" name="pic_tit">帝释天a> div>
- div>
- <div class="fullscreen">
- <div class="page">div>
- <div class="page">div>
- <div class="page">div>
- <div class="page">div>
- <div class="page">div>
- <div class="page">div>
- <div class="page">div>
- div>
- body>
- <script>
- window.onload = init;
- window.onresize = init;
- function init() {
- var oPtits = document.querySelectorAll(".shishen a")
- var fp = document.querySelector(".fullscreen");
- var pages = document.querySelectorAll(".page");
- var index = 0;
- var vh = document.documentElement.clientHeight;
- for (var i = 0; i < pages.length; i++) {
- pages[i].style.height = vh + "px";
- }
- // document.onmousewheel=throttle(mover,500)
- document.addEventListener("mousewheel", throttle(move,1000));//非火狐
- document.addEventListener("DOMMouseScroll", throttle(move,1000));//火狐
- function move(ev) {
- if (getWD(ev) > 0) {
- index--;
- if (index < 0) {
- index = 0;
- }
-
- } else {
- index++;
- if (index >= pages.length - 1) {
- index = pages.length - 1
- }
- }
- changeColor(index)
- }
- oPtits.forEach((item, k) => {
- item.onclick = function () {
- index = k;
- changeColor(index)
- }
- })
- function changeColor(idx) {
- for (var j = 0; j < oPtits.length; j++) {
- oPtits[j].classList.remove("active")
- }
- oPtits[idx].classList.add("active")
- fp.style.top = -idx * vh + "px"
- }
- function getWD(ev) {
- if (ev.wheelDelta) {
- return ev.wheelDelta;
- } else if (ev.detail) {
- return ev.detail * -40;
- }
- }
- function throttle(handler, wait) {
- var lastTime = 0;
- return function (e) {
- var nowTime = new Date().getTime();
- if (nowTime - lastTime >= wait) {
- lastTime = nowTime;
- handler.apply(this, arguments);
- }
- }
- }
-
- }
-
- script>
当我们右击网页的时候,会自动出现windows自带的菜单。那么我们可以使用contextmenu事件来修改我们指定的菜单,但前提是把右击的默认行为取消掉。
var text = document.getElementById('text');
addEvent(text, 'contextmenu', function (evt) {
var e = evt || window.event;
preDef(e);
var menu = document.getElementById('menu');
menu.style.left = e.clientX + 'px';
menu.style.top = e.clientY + 'px';
menu.style.visibility = 'visible';
addEvent(document, 'click', function () {
document.getElementById('myMenu').style.visibility = 'hidden';
});
案例
- <style>
- *{
- margin: 0;
- padding: 0;
- }
- .box {
- width: 1000px;
- margin: 0 auto;
- height: 800px;
- background: #1FA2FF;
- /* fallback for old browsers */
- background: -webkit-linear-gradient(to right, #A6FFCB, #12D8FA, #1FA2FF);
- /* Chrome 10-25, Safari 5.1-6 */
- background: linear-gradient(to right, #A6FFCB, #12D8FA, #1FA2FF);
- /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
-
-
- }
-
- .list {
- position: absolute;
- left: 0;
- top: 0;
- padding: 4px;
- line-height: 40px;
- list-style: none;
- background: #1CD8D2;
- visibility: hidden;
- /* fallback for old browsers */
- background: -webkit-linear-gradient(to right, #93EDC7, #1CD8D2);
- /* Chrome 10-25, Safari 5.1-6 */
- background: linear-gradient(to right, #93EDC7, #1CD8D2);
- /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
- text-align: center;
- border: 1px solid #fff;
- border-radius: 7px;
- }
-
- a {
- color: #fff;
- text-decoration: none;
- }
-
- li:hover a {
- color: #FF8008;
- }
- style>
- head>
-
- <body>
- <div class="box">
-
- div>
- <ul class="list">
- <li><a href="javascript:;">刷新本页面a>li>
- <li><a href="https://www.taobao.com/">去淘宝a>li>
- <li><a href="https://www.jd.com/">去京东a>li>
- ul>
- body>
- <script>
- var oDiv=document.querySelector(".box")
- var oUl=document.querySelector(".list")
- var oLis=document.querySelectorAll(".list li")
- oDiv.addEventListener("contextmenu",function(ev){
- ev.preventDefault()//阻止原本的菜单
- var x=ev.pageX;
- var y=ev.pageY;
- var ulWidth=oUl.offsetWidth;//ul盒子宽度
- var ulHeight=oUl.offsetHeight;//ul盒子宽度
- var divRight=oDiv.getBoundingClientRect().right
- var divBottom=oDiv.getBoundingClientRect().bottom
- if(x>=divRight-ulWidth){
- x=divRight-ulWidth;
- }
- if(y>=divBottom-ulHeight){
- y=divBottom-ulHeight;
- }
- oUl.style.visibility="visible"
- oUl.style.left=x+"px"
- oUl.style.top=y+"px"
- })
- document.addEventListener("click",function(){
- oUl.style.visibility="hidden"
- })
- oLis[0].onclick=function(){
- location.reload();
- }
- script>
touchstart:触摸开始的时候触发
touchmove:手指在屏幕上滑动的时候触发
touchend:触摸结束的时候触发
每个触摸事件都包括了三个触摸列表,每个列表里包含了对应的一系列触摸点(用来实现多点触控)
事件属性
touches:当前位于屏幕上的所有手指的列表。
targetTouches:位于当前DOM元素上手指的列表。
changedTouches:涉及当前事件手指的列表。clientX/ clientY:// 触摸点相对于浏览器窗口viewport的位置
pageX / pageY:// 触摸点相对于页面的位置
screenX/screenY ://触摸点相对于屏幕的位置
上面三者表示动作在屏幕上发生的位置(page包含滚动距离,client不包含滚动距离,screen则以屏幕为基准)
e.targetTouches[0].pageX 获取到 触摸点相对页面的x坐标
- <script>
- var oDiv = document.getElementById("box");
- oDiv.addEventListener("touchmove", function (ev) {
- // console.log(ev);// TouchEvent
- // console.log(ev.changedTouches);//屏幕上手指列表
- // console.log(ev.changedTouches[0]);
- // console.log(ev.targetTouches[0]);
- // console.log(ev.changedTouches[0].clientX);
- var x = ev.changedTouches[0].clientX;
- var y = ev.changedTouches[0].clientY;
- oDiv.style.left = x - oDiv.offsetWidth / 2 + "px";
- oDiv.style.top = y - oDiv.offsetHeight / 2 + "px";
- })
-
- // touchstart 屏幕触摸开始时触发
- // touchend 屏幕触摸结束时触发
- // touchmove 触摸移动时触发
- script>
- <body>
- <div class="box">
- 欢迎你,<span class="nickname">span>
- <a href="javascript:;" class="logout">退出a>
- div>
- body>
- <script>
- var ospan = document.querySelector(".box .nickname");
- var oA = document.querySelector(".box .logout");
- var uname = "dyz";
- // localStorage.setItem("name", uname);
- localStorage.name = uname;
-
- // console.log(localStorage.getItem("name"));
- ospan.innerHTML = localStorage.getItem("name");
-
- oA.onclick = function () {
- localStorage.removeItem("name");
- }
-
- 本地存储
- 存数据
- localStorage.setItem(key, value)
- localStorage.key = value
-
- 取数据
- localStorage.getItem(key)
- localStorage.key
-
- 删除一条数据数据
- localStorage.removeItem(key)
-
- 清空所有数据
- localStorage.clear()
-
- script>
- <body>
- <form action="">
- 用户名:<input type="text" name="uname"><br>
- 密码:<input type="password" name="pwd"><br>
- <input type="button" value="登录">
- form>
- body>
- <script>
- var user = document.querySelector("input[name='uname']")
- var pwd = document.querySelector("input[name='pwd']")
- var btn = document.querySelector("input[type='button']");
- btn.onclick = function () {
- var uv = user.value;
- //表单验证
- console.log(localStorage.getItem('user'));
- if (true) {//表单验证成功
- var t = confirm("是否记住用户名");
- if (t) {
- localStorage.setItem("user", uv);
- location.reload();
- }
- }
- }
-
- if (localStorage.getItem("user") !== null) {
- user.value = localStorage.getItem("user");
- }
-
-
- script>