HTML 在线日记本:带保存、清空、标记功能
<!DOCTYPE html>
<html>
<head>
<title>HTML 在线日记本</title>
<style>
#content {
width: 400px;
height: 400px;
border: 1px solid black;
margin-bottom: 10px;
overflow: auto;
padding: 10px;
}
#toolbar {
margin-bottom: 10px;
}
.marker {
background-color: yellow;
position: absolute;
border: 1px solid black;
padding: 5px;
}
</style>
</head>
<body>
<div id="toolbar">
<button onclick="save()">保存</button>
<button onclick="clearContent()">清空</button>
<button onclick="toggleMarker()">标记</button>
</div>
<div id="content" contenteditable="true"></div>
<script>
// 保存内容到本地存储
function save() {
const content = document.getElementById("content").innerHTML;
localStorage.setItem("diary", content);
alert("保存成功!");
}
// 从本地存储中加载内容
function load() {
const content = localStorage.getItem("diary");
if (content) {
document.getElementById("content").innerHTML = content;
}
}
// 清空内容
function clearContent() {
document.getElementById("content").innerHTML = "";
}
// 切换标记功能
function toggleMarker() {
const content = document.getElementById("content");
content.classList.toggle("marker");
if (content.classList.contains("marker")) {
content.addEventListener("mousedown", startMarker);
} else {
content.removeEventListener("mousedown", startMarker);
}
}
// 开始标记
function startMarker(e) {
e.preventDefault();
const marker = document.createElement("span");
marker.classList.add("marker");
e.target.appendChild(marker);
document.addEventListener("mousemove", moveMarker);
document.addEventListener("mouseup", stopMarker);
}
// 移动标记
function moveMarker(e) {
const marker = document.querySelector("#content .marker");
marker.style.left = `${e.clientX}px`;
marker.style.top = `${e.clientY}px`;
}
// 停止标记
function stopMarker(e) {
document.removeEventListener("mousemove", moveMarker);
document.removeEventListener("mouseup", stopMarker);
}
// 加载已保存的内容
load();
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/jB7H 著作权归作者所有。请勿转载和采集!