首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在文本区域中呈现HTML

在文本区域中呈现HTML
EN

Stack Overflow用户
提问于 2011-01-16 22:23:26
回答 6查看 280.7K关注 0票数 167

我需要能够在一个文本区域内呈现一些HTML标签(即,,,),但是文本区域只将它们的内容解释为文本。有没有一种不依赖外部库/插件的简单方法(我使用的是jQuery)?如果没有,你知道有什么jQuery插件可以用来做这件事吗?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-01-16 22:28:59

这在textarea中是不可能做到的。您正在寻找的是一个content editable div,这非常容易完成:

代码语言:javascript
复制
<div contenteditable="true"></div>

jsFiddle

代码语言:javascript
复制
div.editable {
    width: 300px;
    height: 200px;
    border: 1px solid #ccc;
    padding: 5px;
}

strong {
  font-weight: bold;
}
代码语言:javascript
复制
<div contenteditable="true">This is the first line.<br>
See, how the text fits here, also if<br>there is a <strong>linebreak</strong> at the end?
<br>It works nicely.
<br>
<br><span style="color: lightgreen">Great</span>.
</div>

票数 267
EN

Stack Overflow用户

发布于 2014-11-24 02:28:55

通过一个可编辑的div,您可以使用方法document.execCommand (more details)轻松地为您指定的标记和其他一些功能提供支持。

代码语言:javascript
复制
#text {
    width : 500px;
	min-height : 100px;
	border : 2px solid;
}
代码语言:javascript
复制
<div id="text" contenteditable="true"></div>
<button onclick="document.execCommand('bold');">toggle bold</button>
<button onclick="document.execCommand('italic');">toggle italic</button>
<button onclick="document.execCommand('underline');">toggle underline</button>

票数 36
EN

Stack Overflow用户

发布于 2018-04-14 12:01:53

因为你只说了渲染,是的,你可以。你可以这样做:

代码语言:javascript
复制
function render(){
	var inp     = document.getElementById("box");
	var data = `
<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml" 
style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;">
${inp.value} <i style="color:red">cant touch this</i>
</div>
</foreignObject>
</svg>`;
	var blob = new Blob( [data], {type:'image/svg+xml'} );
	var url=URL.createObjectURL(blob);
	inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")";
 }
 onload=function(){
  render();
  ro = new ResizeObserver(render);
	ro.observe(document.getElementById("box"));
 }
代码语言:javascript
复制
#box{
  color:transparent;
  caret-color: black;
  font-style: normal;/*must be same as in the svg for caret to align*/
  font-variant: normal; 
  font-size:13.3px;
  padding:2px;
  font-family:monospace;
}
代码语言:javascript
复制
<textarea id="box" oninput="render()">you can edit me!</textarea>

这使得textarea可以呈现html!除了调整大小时的闪烁,不能直接使用类,以及必须确保svg中的div具有与插入符号正确对齐的textarea相同的格式,它是有效的!

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4705848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档