六個(gè)有用的 JavaScript 代碼片段
關(guān)于代碼素材,我想每個(gè)開(kāi)發(fā)者都有屬于自己的代碼素材庫(kù),我今天這篇文章分享的是我的代碼素材庫(kù)內(nèi)容,雖然不一定適合所有人,但是我還是想將它分享出來(lái),只希望對(duì)一些人有用即可。
1.文件內(nèi)容上傳
var selectContent=document.getElementById("selectContent");
var contentForSelection=document.getElementById("contentForSelection");selectContent.onchange=function(e) {
if (!window.FileReader) {
alert("Your browser does not support HTML5 'FileReader' function required to open a file.");
} else {
let fileis = this.files[0];
let fileredr = new FileReader();
fileredr.onload = function (fle) {
let filecont = fle.target.result;
contentForSelection.value=filecont;
};
//fileredr.readAsArrayBuffer(fileis);
fileredr.readAsText(fileis);
}
};
在上面的示例中,由于我選擇導(dǎo)入的文件是文本格式,因此使用方法 readAsText 而不是 readAsArrayBuffer。
改為使用 readAsArrayBuffer 的實(shí)例包括讀取圖像流或讀取 ZIP 存檔文件。
成功導(dǎo)入后,文件內(nèi)容將自動(dòng)呈現(xiàn)到元素 ID 為“contentForSelection”的文本區(qū)域中。
2.保存文件內(nèi)容
var saveBtn=document.getElementById("saveBtn");
var cnotallow=document.getElementById("contentForSelection");
saveBtn.notallow=function() {
let txtCnotallow=contentForSelection.value;
if (!window.Blob) {
alert("Your browser does not support HTML5 'Blob' function required to save a file.");
} else {
let textblob = new Blob([txtContent], {
type: "text/plain"
});
let dwnlnk = document.createElement("a");
dwnlnk.download = "output.txt";
dwnlnk.innerHTML = "Download File";
if (window.webkitURL != null) {
dwnlnk.href = window.webkitURL.createObjectURL(textblob);
}
dwnlnk.click();
}
};
上面的代碼片段通常在在線(xiàn)筆記應(yīng)用程序中實(shí)現(xiàn),以便用戶(hù)導(dǎo)出他們的輸出。 或者,在諸如數(shù)據(jù)/代碼格式化程序之類(lèi)的 Web 實(shí)用程序中,通常也會(huì)提供 [Save] 功能,以允許用戶(hù)將后續(xù)格式化的文本內(nèi)容保存到本地存儲(chǔ)文件中。
3.復(fù)制到剪貼板
復(fù)制到剪貼板是基于瀏覽器的設(shè)置中的另一個(gè)經(jīng)典功能。
通常情況下,如果轉(zhuǎn)換后的輸出僅用于一次性任務(wù),則不需要將輸出保存到文件中,使用以下 JS 代碼片段會(huì)更合適:
var copyBtn=document.getElementById("copyBtn");
var cnotallow=document.getElementById("contentForSelection");
copyBtn.notallow=function(evt) {
copyBtn.nextElementSibling.innerHTML="";
copyTransformedOutput("contentForSelection");
let smallEle=evt.currentTarget.nextElementSibling;
smallEle.innerHTML="<span style='color:green'> Copied to Clipboard!</span>";
};
function copyTransformedOutput(inputEleId) {
let copyText = document.getElementById(inputEleId);
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
navigator.clipboard.writeText(copyText.value);
}
請(qǐng)注意,我選擇在成功復(fù)制代碼片段后顯示一條消息“已復(fù)制到剪貼板”。
因此,轉(zhuǎn)換后的輸出隨后可以粘貼到別處,而無(wú)需存儲(chǔ)到本地文件中以供使用。
4.全部查找和替換
雖然在最新的 JavaScript 控制臺(tái)中此功能目前是內(nèi)置的,但由于其實(shí)現(xiàn)的獨(dú)創(chuàng)性和簡(jiǎn)單性,了解以下 JavaScript 函數(shù)仍然是相關(guān)且有用的:
function replaceAll(inputStr,toReplace,replaceWith) {
return inputStr.split(to
Replace).join(replaceWith);
}
例如,如果我想在文本區(qū)域中用“ID”替換“id”:
代碼片段的其余部分是這樣的:
var replaceBtn=document.getElementById("replaceBtn");
replaceBtn.notallow=function() {
let toFind=document.getElementById("ToFind").value;
let replaceWith=document.getElementById("ReplaceWith").value;
contentForSelection.value=replaceAll(contentForSelection.value,toFind,replaceWith);
};
5. 生成隨機(jī)十六進(jìn)制顏色
我發(fā)現(xiàn)這個(gè) JavaScript 方法被低估的情況是當(dāng)我不得不在同一個(gè) Web 應(yīng)用程序上渲染多條行車(chē)路線(xiàn)時(shí):
顯然微分無(wú)窮大。 不同顏色的重疊駕駛路線(xiàn)更容易讓任何觀(guān)眾比較和對(duì)比顯示在地圖可視化上的各種路線(xiàn)。 因此,動(dòng)態(tài)生成不同的顏色是必要的,并且可以通過(guò)以下方式實(shí)現(xiàn):
function generateRandomHexColor() {
let colorGenerated="#" + (Math.random() * 0xfffff * 1000000).toString(16).slice(0, 6);
if(colorGenerated !== "#0000ff" && colorGenerated !== "#ff0000") {
return colorGenerated;
}
colorGenerated="#" + (Math.random() * 0xfffff * 1000000).toString(16).slice(0, 6);
}
6. 突出顯示 JSON 語(yǔ)法
對(duì)于地圖服務(wù)提供商返回的每條路線(xiàn),我都合并了路線(xiàn) JSON 數(shù)據(jù)輸出的導(dǎo)出功能。
因此,為了區(qū)分JSON對(duì)象中的String、Float、Integer、Boolean等對(duì)象類(lèi)型,我選擇了顏色編碼,如下所示:
以上效果可以通過(guò) CSS 和 JavaScript 實(shí)現(xiàn)。
JavaScript 代碼:
function syntaxHighlight(json) {
json = json.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = "number";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "key";
} else {
cls = "string";
}
} else if (/true|false/.test(match)) {
cls = "boolean";
} else if (/null/.test(match)) {
cls = "null";
}
return "<span class='" + cls + "'>" + match + "</span>";
});
}
CSS 代碼:
.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: red;
}
今天這篇文章中的6 個(gè) 有用的JavaScript 代碼片段就到此結(jié)束了,希望對(duì)你有用。