以下代码允许任何网站暂时完全可编辑:
document.body.contentEditable = "true";
如果我想使用此方法保存对特定网站所做的设置,如何使用 Javascript 和 PHP(如果需要)实现此目的,以便下次我访问此 URL 时,该网站会自动更新所做的设置。这可能吗?是否已有可用的扩展程序?
最佳答案
这里有一种使用普通 JS 可以做到这一点的方法。
这是 JSFiddle因为 StackOverflow 不允许 localStorage
作为安全功能在网站上执行。
工作原理:
- 使用
window.onload = function() {...}
, 检查是否'content'
key 存在于localStorage
- 如果是,将数据载入
<div class="content">
- 按下
Edit
按钮,contentEditable
已切换 - 在这里您可以使用任何方法来保存数据。我用了
content.contentEditable === 'false'
保存innerHTML
数据到'content'
键。
注意: localStorage
保存在本地浏览器中,使用数据库或任何类似的东西向所有观众显示编辑。
// Load content onload if it exists in localStorage
window.onload = function() {
if(localStorage.getItem('content')) {
document.querySelector('.content').innerHTML = localStorage.getItem('content');
}
}
let editBtn = document.querySelector('#edit_content');
let content = document.querySelector('.content');
editBtn.addEventListener('click', () => {
// Toggle contentEditable on button click
content.contentEditable = !content.isContentEditable;
// If disabled, save text
if(content.contentEditable === 'false') {
localStorage.setItem('content', content.innerHTML);
}
});
.content {
border: 1px solid;
padding: 15px;
}
<div class="content">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
<br>
<button id="edit_content">Edit</button>
关于javascript - 保存在任何网站上可编辑的内容所做的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876234/