我正在创建一个页面,您可以在其中输入HTML并在div中查看输出.
码:
$("#tryit").keyup(function() {
var input = $(this).val();
$("#readout").html(input);
});Run Code Online (Sandbox Code Playgroud)
#readout {
height: 400px;
width: 48%;
border: 1px solid black;
overflow: auto;
float: right;
clear: none;
display: inline-block;
}
#tryit {
height: 396px;
width: 50%;
float: left;
clear: none;
display: inline-block;
font-family: monospace;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="tryit" id="tryit" rows="10"><!doctype html> <html> <head> <title>New Webpage</title> </head> <body> </body> </html>
</textarea>
<div id="readout"></div>Run Code Online (Sandbox Code Playgroud)
它按预期工作:它将HTML输出到#readout.出现问题的是当用户在中添加<style>标签时head.然后添加的样式不仅会影响文本输入中的HTML,还会影响整个页面中的HTML.
如何使CSS仅影响用户的输入,而不影响整个页面?
这是问题页面.
您确实应该考虑使用不同的方法来实现这一目标。
如果您确实想使用目前为止所拥有的内容,则必须替换 textarea 值中的许多内容。只是为了给您一个想法,在下面的代码片段中,我仅用( #readouthtml ) 替换和body样式声明,以将样式应用于#readout而不是页面的。它确实适用于,但所有其他可能的声明又如何呢?id divbodybody
当然,当谈到正则表达式时,我是一个真正的菜鸟,我确信这可以做得更好,但所有这些都是不必要的。
$("#tryit").keyup(function() {
var style = $(this).val().match(/<style>(.*)<\/style>/);
if (style !== null && style.length > 0) {
var bodyReplace = style[1].replace(/(^|\s)(html)|(body)(\s|$)/ig, '#readout');
}
var input = $(this).val();
$("#readout").html(input.replace(/<style>.*<\/style>/, '<style>'+bodyReplace+'</style>'));
});
$("#tryit").keyup();Run Code Online (Sandbox Code Playgroud)
#readout {
height: 400px;
width: 48%;
border: 1px solid black;
overflow: auto;
float: right;
clear: none;
display: inline-block;
}
#tryit {
height: 396px;
width: 50%;
float: left;
clear: none;
display: inline-block;
font-family: monospace;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="tryit" id="tryit" rows="10"><!doctype html> <html> <head> <title>New Webpage</title><style>body {background: black; color: red }</style> </head> <body><h1>Hello</h1> </body> </html>
</textarea>
<div id="readout"></div>Run Code Online (Sandbox Code Playgroud)
另一个问题是您中的<doctype>、<html>、<head>和元素并不真正存在。看一下来源,你会发现它们不在那里,也不属于那里。话虽这么说,我会采用Barmar评论中提到的解决方案,他建议使用.<body>textareaiframe
其实实现起来并不难。blob一种快速但肮脏的方法是从 textarea 中创建 avalue并将其添加到 的源属性中iframe。通过为 CSS 设置另一个文本区域并将其value作为样式表注入到iframe. 由于沙箱安全问题,我无法使用iframeSO 片段工具中的东西,请检查此内容
我相信你会明白的。
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |