如何允许文本区域的双向编辑和实时预览
我正在尝试设置一个简单的“目录”预览器,其中包含一个文本区域,您可以在其中粘贴文章的 HTML,以及一个仅显示标题的“实时预览”容器。
除了通过文本区域进行编辑之外,我还希望能够编辑标题文本或更改标题的属性(CSS 类和 h 级别(h1/h2/h3/等))并将这些更改反映在文本区域中。
您会推荐什么方法?我知道有一些 jQuery 就地编辑插件,但我想知道这是否太过分了,或者是否有更直接的方法来做到这一点。
我现在的代码如下。你有什么建议吗? “工作”版本位于 http://jsfiddle.net/supertrue/6zeWQ/
// selector for the source textarea
var source = $('textarea#source');
// selector for the destination
var destination = $('#toc');
// interface for changing header level and css class
var gui = '<select><option value="h2">h2</option><option value="h3">h3</option><option value="h4">h4</option></select><input type="checkbox" name="hidden" value="Hide?" /> ';
source.keyup(function() {
var html = '<div>' + source.val() + '</div>';
var hs = $(html).find('h1,h2,h3,h4,h5,h6');
destination.empty().append(hs);
$('#toc h2,#toc h3,#toc h4,#toc h5').prepend(gui);
});
I am trying to set up a simple "table of contents" previewer that consists of a textarea where you paste the HTML of an article, and a 'live preview' container showing just the headers.
In addition to editing via the textarea, I'd also like to be able to edit the header text or change header's attributes (CSS class and h level (h1/h2/h3/etc)) and have those changes reflected in the textarea.
What approach would you recommend? I know there are a few jQuery edit in place plugins, but I'm wondering if that's overkill or if there's a more direct way to do it.
The code I have now is below. Do you have suggestions? The 'working' version is on http://jsfiddle.net/supertrue/6zeWQ/
// selector for the source textarea
var source = $('textarea#source');
// selector for the destination
var destination = $('#toc');
// interface for changing header level and css class
var gui = '<select><option value="h2">h2</option><option value="h3">h3</option><option value="h4">h4</option></select><input type="checkbox" name="hidden" value="Hide?" /> ';
source.keyup(function() {
var html = '<div>' + source.val() + '</div>';
var hs = $(html).find('h1,h2,h3,h4,h5,h6');
destination.empty().append(hs);
$('#toc h2,#toc h3,#toc h4,#toc h5').prepend(gui);
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于听起来您想做的事情,您需要使用至少一个 iframe 来构建编辑器,其中将包含您想要编辑的样式文本。只需在 iframe 内设置 document.designmode = "on" 即可。
For what it sounds like you want to do, you'll need to build your editor using at least one iframe, which will contain the styled text that you want to edit. Just set document.designmode = "on" inside the iframe.