在我的项目中,我有一个div,它是一个文本区域,我可以将文本换成代码格式。
我还有一个带有id="preview"
在前端视图中单击预览按钮时,是否可以在另一个div中显示文本区域的输出 ,就像在IE上或FIREFOX。
Codepen示例: http://codepen.io/riwakawebsitedesigns/pen/lfpKF
HMTL代码
<div class="container">
<textarea id="widget">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus repellendus inventore, voluptatum ipsa ipsum debitis voluptates, laudantium nulla odio sed, pariatur quaerat quae numquam beatae ad odit optio quasi magni explicabo tenetur. Consectetur, animi, autem? Non laboriosam ad nisi, commodi, dolores soluta. Dolorum error unde itaque ipsum a? Libero sapiente eligendi similique, itaque deserunt aliquid magnam ducimus nesciunt, iste ad nihil labore assumenda soluta earum. Rerum deserunt totam aperiam maiores facere eum sapiente modi non debitis consectetur voluptatum, voluptatibus labore repellendus tempora voluptate error nesciunt eaque possimus. Consectetur laborum ab ipsum, voluptate perspiciatis quos omnis delectus dicta mollitia atque voluptates!</textarea>
<div class="buttons">
<button id="code">Code</button>
<button id="preview">Preview</button>
</div>
<!-- Should display live out put of wraped code.-->
<div id="preview" class="code-preview"></div>
</div>
的Javascript
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$('#bold').click(function() {
wrapText("widget", "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("widget", "<em>", "</em>");
});
$('#underline').click(function() {
wrapText("widget", "<u>", "</u>");
});
$('#code').click(function() {
wrapText("widget", "<pre><code>", "</code></pre>");
});
答案 0 :(得分:3)
更改您的预览按钮ID,如下所示:
<button id="preview-btn">Preview</button>
在你的JS中:
$('#preview-btn').on('click', function () {
$('#preview').html($('#widget').val());
});