JS之localStorage实战
目标:用localStorage记录下滑动条的进度,下次打开不变
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#slide{position: relative;width: 600px;height: 30px;border: 1px solid black;margin: 100px auto;}
#block{width: 30px; height: 30px; background-color: blue;position: absolute;left: 0;}
#full{width: 0px;height: 30px;background-color: orange;position: absolute;top: 0px;left: 0px;}
</style>
<script>
window.onload = function(){
var oSlide = document.getElementById("slide");
var oFull = document.getElementById("full");
var oBlock = document.getElementById("block");
if(!window.localStorage){
alert("该浏览器不支持!");
}else{
var l = localStorage.getItem("slide") ? localStorage.getItem("slide") : 0;
oBlock.style.left = l + 'px';
oFull.style.width = l + 'px';
}
oBlock.onmousedown = function(ev){
var e = ev || window.event;
var offestX = e.clientX - oBlock.offsetLeft;
document.onmousemove = function(ev){
var e = ev || window.event;
l = e.clientX - offestX;
if(l <= 0){
l = 0;
}
if(l >= 570)
{
l = 570;
}
oBlock.style.left = l + 'px';
//填充部分要跟随滑块填充
oFull.style.width = l + 'px';
//对当前滑块的位置,进行本地存储
if(!window.localStorage){
alert("该浏览器不支持!");
}else{
localStorage.setItem("slide",l);
}
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
</head>
<body>
<div id = 'slide'>
<div id = 'full'></div>
<div id = 'block'></div>
</div>
</body>
</html>
实现效果:
相关知识:
JS之localStorage