繁体   English   中英

使用jQuery将父选择器添加到CSS块

[英]Adding Parent Selectors To CSS block using jQuery

因此,我们有一个电子邮件构建器,可让客户创建自己的自定义配色方案。 除了预定义的字段,我们允许他们输入自己的自定义CSS块以修改其配色方案。

问题是我们需要在每个规则之前放置一个父选择器。 因此,例如:

 p {font-size:12px;}

将需要成为

 .parent_selector p {font-size:12px;}

无论如何,以编程方式将这些父选择器添加到每个CSS规则? 作为一个用例示例,假设这是客户端提供的定制css:

 p {font-size:12px; font-weight:bold}
 .description {color:#cccccc; line-height:1.2em;}
 #header {padding:bottom:12px}
 .buttons .button {padding:12px; background:#112233;}
 .buttons a {text-decoration:none;}

在每个规则之前,我都需要一个父选择器。 我考虑过搜索方括号并相应地添加文本,但这太复杂了。 另一个选择(我不喜欢)是创建一个虚拟选择器并进行字符串替换。 这是一个例子:

 .placeholder p {font-size:12px;}

将需要成为

 .parent_selector p {font-size:12px;}

提前致谢!

您可以尝试将其代码注入不太像预处理器的代码中,然后在发送到服务器之前进行编译。 或创建自己的解析器,以将父选择器添加到所提供的类之前。 这可能需要您的用户可以输入的不同格式的工作。

编辑:再三考虑,不要碰碰运气。 删除所有双空格字符,您将免费获得一致的格式和缩小字符。

 function addParentSelector( parentSelector, styles ){ return styles.replace(/((?:\\s|\\n|\\t)+)/gm, ' ').replace(/([^{]+)({[^}]+})/gm, function(_, selectors, styles ){ return selectors.split(',').map(function( selector ){ return parentSelector + ' ' + selector; }).join(',') + styles; }); } function compile(){ var res = addParentSelector('.some-parent-selector', document.querySelector('#styles').value ); document.querySelector('#output').innerHTML = res; } 
 /* ignore the css here */ textarea { width: 100%; height: 6em; } pre { white-space:pre-wrap; word-wrap:break-word; } button { cursor: pointer; display: inline-block; text-align: center; color: #fff; line-height: 1; padding: .6em .8em; background: #009afd; -webkit-transition: background 0.15s ease, color 0.15s ease; -moz-transition: background 0.15s ease, color 0.15s ease; -ms-transition: background 0.15s ease, color 0.15s ease; -o-transition: background 0.15s ease, color 0.15s ease; border: 1px solid #1777b7; box-shadow: 0 1px 0 rgba(255,255,255,0.3) inset,0 1px 1px rgba(100,100,100,0.3); border-radius: 3px; } button:hover { color: #fff; background: #0087de; } 
 <textarea id='styles'> .profile { line-height: 2; padding: 1em; font-family: sans-serif; } .profile__header { background: red; } .profile__header-heading { font-size: 2em; padding: 0; margin: 0; } .profile__header-heading small { color: rgba(43,44,43,.7); } .profile__header-edit { padding: .5em 2em; border: .2em solid #3cf; color: #fff; background: #3cf; text-decoration: none; transition: .2s; } .profile__header-edit:hover { color: #3cf; background: #fff; } .profile__content p { color: rgba(34,35,34,.7); line-height: 2; } </textarea> <button onclick="compile()">click me!</button> <pre id="output"></pre> 

编辑:正则表达式中有一个问题。 我正在使用[\\ s | \\ n | \\ t]组作为空格|换行符|制表符,但它应该是一个非捕获组(?:\\ s | \\ n | \\ t)。

这应该更完整。 另外请注意, Array.prototype.map()在IE <9中将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM