[英]Add parent class to css inside style tags
我正在創建的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樣式的支持充其量是偽劣的,在某些情況下,最好放在體內。 它令人沮喪,但我必須與目標合作。
嘗試這個。
我遍歷dom中的所有樣式元素,存儲規則,並在存儲時將其從dom中刪除。
然后構建較少的樣式表,包括發現的樣式規則。
最后,檢索較少的腳本並解析樣式規則,將其添加到主體,然后將主類設置為主體。
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.