Touch事件
touch事件在用户触摸屏幕时触发。其与mouse事件的最大区别在于其支持多点触控。主要有以下几种:
touchstart:相当于mousedown事件
touchmove:相当于mousemove事件
touchend:相当于mouseup事件
应用如下:
<style>
.divtouch{
width:300px;
height:500px;
border:1px solid blue;
position:relative;
margin:0 auto;
}
.divtouch p{
font-size:30px;
text-align:center;
}
.divtouch div{
position:absolute;
width:50px;
height:50px;
background-color:pink;
top:0;
left:0;
}
</style>
<div class="divtouch">
<p></p>
<div></div>
</div>
<script>
var para=document.querySelector(".divtouch p");
var divtouchBlock=document.querySelector(".divtouch div");
var s={
startX:0,
startY:0,
endX:0,
endY:0,
disX:0,
disY:0,
ofl:0,
oft:0,
}
divtouchBlock.addEventListener("touchstart",function(e){
var e=e||window.event;
para.innerHTML=e.touches.length+"根手指";
s.ofl=divtouchBlock.offsetLeft;
s.oft=divtouchBlock.offsetTop;
s.startX=e.touches[0].clientX;
s.startY=e.touches[0].clientY;
e.preventDefault();
},false)
document.addEventListener("touchmove",function(e){
var e=e||window.event;
if(e.touches.length!=1){
return;
}
s.endX=e.touches[0].clientX;
s.endY=e.touches[0].clientY;
s.disX=s.endX-s.startX+s.ofl;
s.disY=s.endY-s.startY+s.oft;
divtouchBlock.style.left=s.disX+"px";
divtouchBlock.style.top=s.disY+"px";
},false)
</script>
设备事件——方向API(陀螺仪)
方向事件指DeviceOrientationEvent,其触发事件为deviceorientation
if(window.DeviceOrientationEvent){
window.addEventListener("deviceorientation",function(e){
var e=e||window.event;
e.alpha;//0~360度,0度指向正北方(Z轴)
e.beta;//设备前后转-180~180度(X轴)
e.gamma;//设备左右转-90~90度(Y轴)
},false)
}
设备事件——加速度API
加速度事件指DeviceMotionEvent,其触发事件为devicemotion
if(window.DeviceMotionEvent){
window.addEventListener("devicemotion",function(e){
var e=e||window.event;
e.acceleration.x;//加速度,x代表x方向
e.acceleration.y;
e.acceleration.z;
e.accelerationIncludingGravity.x;//重力加速度,x轴代表x方向
e.accelerationIncludingGravity.y;
e.accelerationIncludingGravity.z;
},false)
}
cookie
cookie是存储于访问者的计算机中的变量。每当同一台计算机通过浏览器请求某个页面时,就会发送这个cookie。可以使用JavaScript来创建和取回cookie的值。
服务器环境下才能设置cookie,每一个域名下最多20个cookie,每一个cookie不超过4kb。
每个cookie都是一个名/值对,如果要一次存储多个名/值对,可以使用分号加空格(; )隔开。document.cookie="userId=123; userName=Jack";
cookie的名或值中不能使用分号(;)、逗号(,)、等号(=)及空格。如需存储用escape()函数进行编码,从而避免乱码出现。
//设置cookie的名字,值,过期时间
setCookie("usename/password",userVal,10);
function setCookie(key,value,days){
var newDate=new Date();
var nowDay=nowDate.getDate();
nowDate.setDate(nowDay+days);
document.cookie=key+"="+value+";expires"+nowDate.toUTCString();
}
//删除cookie,将date设置为过去的时间来删除
setCookie("name","",-1);
localStorageb本地存储
localStorage是HTML5提供的在客户端存储数据的新方法,localStorage是没有时间限制的数据存储
比cookie方便之处在于可以直接调用和删除。
//设置localStorage
localStorage.username=user.value;
//获取localStorage
alert(localStorage.username);
//删除localStorage
localStorage.removeItem("username");
可通过如下代码来对访问页面次数进行计数:
<script>
if(localStorage.pagecount){
localStorage.pagecount=Number(localStorage.pagecount)+1;//localStorage.pagecount为自定义参数
}else{
localStorage.pagecount=1;
}
console.log(localStorage.pagecount);
</script>