直接看最終效果
在瀏覽器里面可以隨時調出記事本,而且內容自動保存不怕丟失

再來看怎么做的
原理其實很簡單
- 主要使用了codeMirror來做編輯器
- 資料保存在本地存盤,編輯器內容變化時會自動存盤,再次打開時會從本地存盤里面讀取并恢復
- 在標簽頁直接打開、從工具列打開記事本,需要安裝chrome插件 https://plugin.csdn.net/
最后來看看代碼怎么寫
1. 創建擴展應用
- 從桌面的
插件擴展圖示進入擴展后臺 - 點擊
添加插件,填寫名稱,選擇本地代碼后確定即可 - 在插件資訊頁面填寫插件描述資訊,上傳插件圖示
這里的觸發詞選項需要說明下,可以簡單理解為插件的唯一標識,輸入這個詞后就會呼叫插件,建議英文+數字



2. 添加代碼
代碼分為html、css、js三部分,和平時寫前端代碼基本一樣,
不過有幾點需要說明下:
- css、js不要和html混在一塊,要不然會報錯
- jqury、codeMirror已經有內置的了,可以使用相對路徑,這樣就不用走網路了,具體可以看下面代碼
html代碼
<html>
<head>
<title>記事本</title>
<script src="/vendor/codemirror/lib/codemirror.min.js"></script>
<script src="/js/jquery-3.5.1.min.js"></script>
<link rel="stylesheet" href="/vendor/codemirror/lib/codemirror.css">
<script src="/vendor/codemirror/keymap/sublime.js"></script>
</head>
<body>
<textarea id="code" name="code"
style="width:100%;height:calc(100vh - 50px);background:#f5f5f5;border: 1px solid #f0f0f5"></textarea>
</body>
</html>
js代碼
js代碼重點有2部分
重點一:codeMirror編輯器使用
創建codeMirror編輯器并添加change事件監聽
editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
lineWrapping: true,
extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }},
mode: "markdown",
keyMap: "sublime",
});
editor.on("change",function(instance, changeObj){
textChangeHandler(instance.getValue())
});
重點二:本地存盤的使用
var storageKey = 'note_storage'
var value = 'test'
// 寫入本地存盤
localStorage[storageKey] = value
// 從本地存盤讀取資料
value = localStorage[storageKey]
完整的js代碼如下
var storageKey = 'note_storage'
var editor
var default_text =
'1. 每次輸入內容后會自動保存的,下次打開內容不會丟失的\n' +
'2. 內容只保存在本地,插件備份功能不會備份該內容,請不要存盤重要資訊\n' +
'3. 編輯器支持sublime快捷鍵'
function textChangeHandler(text){
if(typeof text === undefined || text === null){
text = ''
}
localStorage[storageKey] = text
}
function init(){
var text = localStorage[storageKey]
//console.info('get ' + text)
if(typeof text != undefined && text != null && text != ''){
editor.setValue(text)
}else{
editor.setValue(default_text)
}
}
(function(){
editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
lineWrapping: true,
extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }},
mode: "markdown",
keyMap: "sublime",
});
init()
editor.on("change",function(instance, changeObj){
textChangeHandler(instance.getValue())
});
})()
3. 添加到桌面
- 在桌面點擊右上角圖示進入到添加界面
- 選擇
系統分類,添加記事本即可

總結
最后總結下,寫個真的可以使用的瀏覽器記事本還是很簡單的,當然了這主要還是得益于codeMirror的強大功能,大家都可以來試試吧
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/266392.html
標籤:其他
上一篇:正則運算式必知必會
