老是,请贴一下源码噻
3 回答
/**
*设置带有过期时间的localStorage
*@key,localStorage的关键字
*@v,localStorage的key的值
*@exp,localStorage过期时间,单位毫秒
*/
function set(key, v, exp){
var curTime = new Date().getTime();
try{
localStorage.setItem( key, JSON.stringify({data:v, curtime:curTime, exp:exp}) );
}
catch(e){
console.log("set localStorage failed:"+e);
}
}
/**
*获取带有过期时间的localStorage的值
*@key,localStorage的关键字
*/
function get(key){
try{
var data = localStorage.getItem(key);
}
catch(e){
console.log("get localStorage failed:"+e);
}
var dataObj = JSON.parse(data);
if(new Date().getTime() - dataObj.curtime > dataObj.exp){
console.log("expires:timeout");
}
else{
console.log("data="+dataObj.data);
}
}
set('good', 'luck', 5000);
get('good');
/**
*将图片以canvas的形式保存在localstorage中
*@key 图片名称
*@src 图片相对地址
*/
function setImg(key, src){
var img = document.createElement('img');
//图片加载完成时触发回调函数
img.addEventListener('load', function(){
var imgCanvas = document.createElement('canvas'),
imgContext = imgCanvas.getContext('2d');
imgCanvas.width = this.width;
imgCanvas.height = this.height;
//渲染图片到canvas中
imgContext.drawImage(this, 0, 0, this.width, this.height);
//用data url的形式取出
var imgAsDataURL = imgCanvas.toDataURL('image/png');
//保存到本地存储中
try{
localStorage.setItem(key, imgAsDataURL);
}
catch(e){
console.log("storage failed:" + e);
}
}, false);
}
/**
*从本地取得图片
*/
function getImg(key){
var srcStr = localStorage.getItem(key);
var imgObj = document.createElement('img');
imgObj.src = srcStr;
document.body.appendChild(imgObj);
}
setImg('img1', 'src/img/doll.jpg');
getImg('img1');
举报