I have user-supplied (arbitrary) css that is delivered as a single text string. This string can be stuffed into a style tag, and I can get a DOM element back from that if need be.
This css should only apply to part of the entire document, which I'll be wrapping in a div with a unique id. Given a rule that looks like this
.userclass > .whatever {
background: blue;
}
... I'd like to be able to add #uniqueid
in front of each rule so that it looks like
#uniqueid .userclass > .whatever {
background: blue;
}
This seems non-trivial. I don't believe it's something I can manage in with a clever regex. Are there any methods in javascript that make this easy, or at least manageable?
If the css is put into a style tag, then it becomes possible to access each rule individually via index with .cssRules[n], but even then each rule can target multiple selectors. Is it as simple as a regex substitution there, looking for commas in between that and the first open curly bracket? Is there more to it than this?
Consider that any arbitrary (valid) css might be supplied.
答案 0 :(得分:1)
一个简单的方法: 如果您将样式标签作为字符串获取并在}处进行拆分,然后在每个数组元素的开头添加#uniqueid。随后,您只需要遍历数组并将其转换回单个字符串并将其附加到html。
我不知道您是否有jQuery,但是jQuery中的解决方案看起来像那样。 这适用于每个CSS代码。如果需要,可以通过一些其他调整来美化输出。
Python 3.4.8 (default, Apr 9 2018, 11:43:18)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes import *
>>> PySide2 = CDLL("libpyside.so")
>>> from PySide2.QtWidgets import QApplication, QLabel
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'PySide2'
>>> PySide2
<CDLL 'libpyside.so', handle 10ffb10 at 7fb7c64f5400\>
答案 1 :(得分:1)
我建议将此文件发送到后端的sass预处理程序。然后,您可以导入该css(作为scss)并执行py-contacts --show TestName # shows details of saved contact of person with "TestName" ...
py-contacts --add NewName --number 012345 --email test@mail.com # adds new contact to YAML .. py-contacts --list # shows a list of all saved contacts
。前端上的JS字符串操作可能远非防弹。.
答案 2 :(得分:0)
由于这是一次婚外恋,我个人只是干脆去做...
#uniqueid {
// paste all your css
}
如果这将变得更加常规,那么您肯定要在构建过程中实现预处理器。