您当前位置:首页 > 文章中心 > HTML5+CSS3 > HTML5

HTML5本地SQL实战记事本例子

稿件来源: 阳光企业网站管理系统   撰稿作者: 太阳光   发表日期: 2013-11-05   阅读次数: 232   查看权限: 游客查看

使用html5本地sqlite数据库保存你创建的纸条,刷新或者下次你打开本页面时仍会显示那些纸条。使用支持html5的浏览器试一下。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5本地SQL记事本</title>
<style>
    body{font-size: 12px}
    .note {
        background-color: rgb(255, 240, 70);
        height: 250px;
        padding: 10px;
        position: absolute;
        width: 200px;
        -webkit-box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5);
        box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.5);
    }
    .note:hover .closebutton {display: block}
    .closebutton {
        display: none;
        background-image: url(deleteButton.png);
        height: 30px;
        position: absolute;
        right: -15px;
        top: -15px;
        width: 30px;
    }
    .edit {outline: none}
    .timestamp {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        font-size: 9px;
        background-color: #db0;
        color: white;
        border-top: 1px solid #a80;
        padding: 2px 4px;
        text-align: right;
    }
</style>
<script type="text/javascript">
var obj = {
    sql : null,//数据库
    captured : null,//点击的对象
    highestZ : 0,//最大Z轴
    highestId : 0 //最大ID号
};
try {
    if (window.openDatabase) {
        obj.sql = openDatabase("NoteTest", "1.0", "HTML5 Database API example", 1024*1024*2);
        !obj.sql&&alert("打开本地数据库失败,可能是数据库版本问题或者磁盘没有足够空间!");
    } else {
        alert("不能打开本地数据库,请使用支持本地储存的浏览器浏览!");
    }
} catch(err) {
    obj.sql = null;
    alert("创建数据库失败,可能你的浏览器不支持html5!");
}
//创建一张纸条
function Note(){
    var self = this;
    //创建noteDIV并绑定事件
    var note = document.createElement('div');
    note.className = 'note';
    note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
    note.addEventListener('click', function() { return self.onNoteClick() }, false);
    this.note = note;
    //创建note关闭按钮并绑定事件
    var close = document.createElement('div');
    close.className = 'closebutton';
    close.addEventListener('click', function(e) { return self.close(e) }, false);
    note.appendChild(close);
    //创建note内容编辑区域
    var edit = document.createElement('div');
    edit.className = 'edit';
    edit.setAttribute('contenteditable', true);
    edit.addEventListener('keyup', function() { return self.onKeyUp() }, false);
    note.appendChild(edit);
    this.editField = edit;
    //创建note脚部时间标志
    var ts = document.createElement('div');
    ts.className = 'timestamp';
    note.appendChild(ts);
    this.lastModified = ts;
    //note写入文档
    document.body.appendChild(note);
    return this;
}
//扩展note对象方法
Note.prototype = {
    get id(){
        return this._id || 0;
    },
    set id(x){
        this._id = x;
    },
    get text(){
        return this.editField.innerHTML;
    },
    set text(x){
        this.editField.innerHTML = x;
    },
    get timestamp(){
        return this._timestamp || 0;
    },
    set timestamp(x){
        if (this._timestamp == x)
            return;
        this._timestamp = x;
        var date = new Date();
        date.setTime(parseFloat(x));
        this.lastModified.textContent = "最后修改: " + date.toLocaleDateString()+" "+date.toTimeString().split(" ")[0];
    },
    get left(){
        return this.note.style.left;
    },
    set left(x){
        this.note.style.left = x;
    },
    get top(){
        return this.note.style.top;
    },
    set top(x){
        this.note.style.top = x;
    },
    get zIndex(){
        return this.note.style.zIndex;
    },
    set zIndex(x){
        this.note.style.zIndex = x;
    },
    close: function(event){
        var note = this;
        obj.sql.transaction(function(tx){
            tx.executeSql("DELETE FROM WebKitStickyNotes WHERE id = ?", [note.id]);
        });
        var duration = event.shiftKey ? 2 : .25;
        this.note.style.webkitTransition = '-webkit-transform ' + duration + 's ease-in, opacity ' + duration + 's ease-in';
        this.note.style.webkitTransformOrigin = "0 0";
        this.note.style.webkitTransform = 'skew(30deg, 0deg) scale(0)';
        this.note.style.opacity = 0;
        //var self = this;
        setTimeout(function() { document.body.removeChild(note.note) }, duration * 1000);
    },
    save: function(){
        var note = this;
        obj.sql.transaction(function (tx){
            tx.executeSql("UPDATE WebKitStickyNotes SET note = ?, timestamp = ?, left = ?, top = ?, zindex = ? WHERE id = ?", [note.text, note.timestamp, note.left, note.top, note.zIndex, note.id]);
        });
    },
    saveAsNew: function(){
        this.timestamp = new Date().getTime();
        var note = this;
        obj.sql.transaction(function (tx){
            tx.executeSql("INSERT INTO WebKitStickyNotes (id, note, timestamp, left, top, zindex) VALUES (?, ?, ?, ?, ?, ?)", [note.id, note.text, note.timestamp, note.left, note.top, note.zIndex]);
        });
    },
    onMouseDown: function(e){
        obj.captured = this;
        this.startX = e.clientX - this.note.offsetLeft;
        this.startY = e.clientY - this.note.offsetTop;
        this.zIndex = ++obj.highestZ;
        var self = this;
        if (!("mouseMoveHandler" in this)) {
            this.mouseMoveHandler = function(e) { return self.onMouseMove(e) };
            this.mouseUpHandler = function(e) { return self.onMouseUp(e) }
        }
        document.addEventListener('mousemove', this.mouseMoveHandler, true);
        document.addEventListener('mouseup', this.mouseUpHandler, true);
        return false;
    },
    onMouseMove: function(e){
        if (this != obj.captured)
            return true;
        this.left = e.clientX - this.startX + 'px';
        this.top = e.clientY - this.startY + 'px';
        return false;
    },
    onMouseUp: function(e){
        document.removeEventListener('mousemove', this.mouseMoveHandler, true);
        document.removeEventListener('mouseup', this.mouseUpHandler, true);
        return false;
    },
    onNoteClick: function(e){
        this.editField.focus();
        getSelection().collapseToEnd();
    },
    onKeyUp: function(){
        this.save();
    }
};
function loaded(){
    obj.sql.transaction(function(tx) {
        tx.executeSql("SELECT COUNT(*) FROM WebkitStickyNotes", [], function(result) {
            loadNotes();
        }, function(tx, error) {
            tx.executeSql("CREATE TABLE WebKitStickyNotes (id REAL UNIQUE, note TEXT, timestamp REAL, left TEXT, top TEXT, zindex REAL)", [], function(result) {
                loadNotes();
            });
        });
    });
}
function loadNotes()
{
    obj.sql.transaction(function(tx) {
        tx.executeSql("SELECT id, note, timestamp, left, top, zindex FROM WebKitStickyNotes", [], function(tx, result) {
            for (var i = 0; i < result.rows.length; ++i) {
                var row = result.rows.item(i);
                var note = new Note();
                note.id = row['id'];
                note.text = row['note'];
                note.timestamp = row['timestamp'];
                note.left = row['left'];
                note.top = row['top'];
                note.zIndex = row['zindex'];
                if (row['id'] > obj.highestId)
                    obj.highestId = row['id'];
                if (row['zindex'] > obj.highestZ)
                    obj.highestZ = row['zindex'];
            }
            !result.rows.length&&newNote();//如果没有数据就新建note
        }, function(tx, error) {
            alert('未能检索记录数据库: ' + error.message);
        });
    });
}

function newNote(){
    var note = new Note();
    note.id = ++obj.highestId;
    note.timestamp = new Date().getTime();
    note.left = Math.round(Math.random() * 400) + 'px';
    note.top = Math.round(Math.random() * 500) + 'px';
    note.zIndex = ++obj.highestZ;
    note.saveAsNew();
}
obj.sql&&addEventListener('load', loaded, false);
</script>
</head>
<body>
<p>使用html5本地sqlite数据库保存你创建的纸条,刷新或者下次你打开本页面时仍会显示那些纸条。使用支持html5的浏览器试一下。</p>
<button id="newNoteButton" onclick="newNote()">新建</button>
<script>
    document.getElementById("newNoteButton").disabled = !obj.sql;
</script>
</body>
</html>

在线浏览:请使用Chrome浏览器浏览!

关键词: html5,数据库,opendatabase   编辑时间: 2013-11-05 15:58:18

  • 感到高兴

    0

    高兴
  • 感到支持

    0

    支持
  • 感到搞笑

    0

    搞笑
  • 感到不解

    0

    不解
  • 感到谎言

    0

    谎言
  • 感到枪稿

    0

    枪稿
  • 感到震惊

    0

    震惊
  • 感到无奈

    0

    无奈
  • 感到无聊

    0

    无聊
  • 感到反对

    0

    反对
  • 感到愤怒

    0

    愤怒
0%(0)
0%(0)
共有0 条评论 发言请遵守【相关规定

网友评论

会员头像
发 表同步腾讯微博    验证码:  点击更新请先登陆
  • 暂无评论
关闭模块文章图片 article Pictrue
  • 我的妈妈爸爸
  • 基于koa2+mysql+vue2.0+Element阳光内容管理系统
  • 代码覆盖率工具 Istanbul 入门教程
  • 全栈工程师的武器——MEAN
  • 9款超炫的 CSS3 复选框(Checkbox)
  • 微信开发在线翻译功能
  • CSS3那些不为人知的高级属性
  • 给easyui的datebox添加清空事件
  • flash写字效果
  • kendoUI系列教程之DropDownList下拉菜单
  • kendoUI系列教程之datetimepicker日期时间选择
  • kendoUI系列教程之datepicker日期选择
  • kendoUI系列教程之combobox下拉列表框
  • kendoUI系列教程之colorpicker
  • kendoUI系列教程之calendar日历表
  • kendoUI系列教程之autocomplete自动补齐