我正在创建一个Web应用程序的问题。在页面的左侧,我有一个可编辑的区域,在右侧是一个实时预览。实时预览区域实际上是一个HTML文件,其中包含可以使用编辑区域操作的特制字段。问题是因为用户HTML可以是他们想要的任何东西。一些CSS可以渗透到我的页面的其余部分。用户做的事情并不少见:background:red;在他们的设计中,我的整个页面都是红色的。
所以,对此的解决方案(至少是我提出的解决方案)是将用户样式包装到父类中。然后在预览区域上有该父类。这样用户样式就不会渗透到我的设计中。我正在考虑使用LESS和jQuery这样的东西:
//psuedo code
less.Compile(".ParentClass { " + $("style").html() + "}");
但是,我找不到像这样可以使用的库。有没有人知道我可以将CSS父类附加到标签中的所有元素?
示例:
<div id="Preview">
<style>
div { background: red; }
</style>
<div>I'm red</div>
</div>
会变成:
<div id="Preview">
<style>
#Preview div { background: red; }
</style>
<div>I'm red</div>
</div>
编辑:我知道风格真的应该在头脑中。但是,被操纵的html文档实际上将作为电子邮件发送。电子邮件客户端对CSS样式的支持充其量是劣质的,在某些情况下,最好是在身体中。令人沮丧但我必须与我的目标合作。
答案 0 :(得分:3)
试试这个。
我遍历dom中的所有样式元素,存储规则并在存储时从dom中删除它们。
然后构建less样式表,包括发现的样式规则。
最后,检索less脚本并解析样式规则,将它们添加到正文中,然后将主类设置为正文。
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
//Loop through all style elements in dom, storing the rules and removing them from the dom when stored
var styles = "";
$.each($("style"), function(index, value){
styles += $(value).text();
$(value).remove();
});
//Build the less stylesheet, including the discovered style rules
var lessStyles = ".master { " + styles + " }";
//Retrieve less and parse the style rules, adding them to the body, then set the master class to the body
$.getScript("http://cdnjs.cloudflare.com/ajax/libs/less.js/1.7.0/less.min.js",function(){
var parser = new(less.Parser);
parser.parse(lessStyles, function (err, tree) {
if (err) { return console.error(err) }
var css = tree.toCSS();
$("<style/>").html(css).appendTo("body");
$("body").addClass("master");
});
});
});
</script>
<style type="text/css">
h2{
color:green;
}
</style>
</head>
<body>
<style type="text/css">
.class2{
color:red;
}
</style>
<h1 class="class2">H1</h1>
<h2>H2</h1>
</body>
</html>
答案 1 :(得分:1)
向the <style>
element添加scoped
属性。
浏览器支持目前为awful。