我需要能够在一个文本区域内呈现一些HTML标签(即,,,),但是文本区域只将它们的内容解释为文本。有没有一种不依赖外部库/插件的简单方法(我使用的是jQuery)?如果没有,你知道有什么jQuery插件可以用来做这件事吗?
发布于 2011-01-16 22:28:59
这在textarea
中是不可能做到的。您正在寻找的是一个content editable div,这非常容易完成:
<div contenteditable="true"></div>
div.editable {
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 5px;
}
strong {
font-weight: bold;
}
<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>
发布于 2014-11-24 02:28:55
通过一个可编辑的div,您可以使用方法document.execCommand
(more details)轻松地为您指定的标记和其他一些功能提供支持。
#text {
width : 500px;
min-height : 100px;
border : 2px solid;
}
<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>
发布于 2018-04-14 12:01:53
因为你只说了渲染,是的,你可以。你可以这样做:
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"));
}
#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;
}
<textarea id="box" oninput="render()">you can edit me!</textarea>
这使得textarea
可以呈现html!除了调整大小时的闪烁,不能直接使用类,以及必须确保svg
中的div具有与插入符号正确对齐的textarea
相同的格式,它是有效的!
https://stackoverflow.com/questions/4705848
复制相似问题