今天在头条上看到推送的这个ContentTools文章,一眼就相中了它。可视化前端编辑插件ContentTools所见即所得,看起来是我想要的效果,下面一起看看这款JavaScript插件是怎么使用的吧!
首先下载插件资源,这是开源项目,源码在GitHub上,地址是:https://github.com/GetmeUK/ContentTools
下载后我们找到压缩包中build目录,里面的资源是我们需要的。
下面新建项目,结构如下:
/site
/assets
/images
- ce-drop-above.png
- ce-drop-below.png
- ce-drop-left.png
- ce-drop-right.png
- video.png
- content-tools.min.js
- content-tools.min.css
- icons.woff
准备HTML
<div data-editable data-name="main-content"> <blockquote> Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. </blockquote> <p>John F. Woods</p> </div> <h1 data-editable data-name="heading">Content</h1> <div data-editable data-name=heading> <h1>Content</h1> </div>
js初始化
var editor = ContentTools.EditorApp.get();
editor.init('*[data-editable]', 'data-name');
JavaScript将根据选择器选择的元素初始化编辑区域,以便编辑器编辑。
还可以为编辑器添加保存或取消事件。
editor.addEventListener('saved', function (ev) {
var name, payload, regions, xhr;
// Check that something changed
regions = ev.detail().regions;
if (Object.keys(regions).length == 0) {
return;
}
// Set the editor as busy while we save our changes
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the update content to the server to be saved
function onStateChange(ev) {
// Check if the request is finished
if (ev.target.readyState == 4) {
editor.busy(false);
if (ev.target.status == '200') {
// Save was successful, notify the user with a flash
new ContentTools.FlashUI('ok');
} else {
// Save failed, notify the user with a flash
new ContentTools.FlashUI('no');
}
}
};
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '/save-my-page');
xhr.send(payload);
});
当用户保存页面时,我们使用Ajax将每个区域的内容发送到服务器,当然你可以不保存到服务器。
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/242463.html
