我是javascript的新手开发者,我需要有关代码的帮助。 该计划的实质:
提前谢谢!
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<p>text1</p>
<p>text2</p>
<p>text3</p>
</div>
<div id="sel">place for text</div>
<button onclick="saveText();">Save</button>
<script src="copy.js" charset="utf-8"></script>
</body>
</html>
"use strict"
function getSelectionText() {
var text = "";
var activeEl = document.activeElement;
var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
if (
(activeElTagName == "textarea") || (activeElTagName == "input" &&
/^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
(typeof activeEl.selectionStart == "number")
) {
text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
} else if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
};
var saveText = function() {
var selectionText = getSelectionText();
var selCopy = document.querySelector("#sel");
var createDiv = document.createElement("div");
createDiv.classList.add("copyDiv");
selCopy.appendChild(createDiv);
createDiv.innerHTML = selectionText;
localStorage.setItem('getDiv', document.getElementsByClassName('copyDiv'));
var score = localStorage.getItem('getDiv');
};
答案 0 :(得分:0)
你可以编写window.onload方法,在其中你可以设置id为“sel”的div的内容。像
window.onload = function() {
document.getElementById("sel").innerHTML = localStorage.getItem('getDiv');;
}
答案 1 :(得分:0)
这是将所选文本添加到存储空间的简单方法。
function saveText() {
var text = getSelectionText();
text = text.replace(/(?:\r\n|\r|\n)/g, "<br>"); // Preserve line breaks.
if (localStorage.getItem("savedText") === null) {
localStorage["savedText"] = "";
}
localStorage["savedText"] += "<br><br>" + text;
showText();
}
function showText() {
var innerDiv = "<div class=\"copyDiv\">";
innerDiv += localStorage["savedText"];
innerDiv += "</div>";
document.getElementById("sel").innerHTML = innerDiv;
}
window.onload = function() {
showText();
};