<script id="skinTemplate" type="text/plain"> .text,a.text { color: <%=window.textColor%>; } .window_current .text,.window_current a.text { color: <%=currentWindow.textColor%>; } .titleText, a.titleText { color: <%=window.titleColor%>; font-weight: <%=window.titleFontWeight%>; } .window_current .titleText,.window_current a.titleText { color: <%=currentWindow.titleColor%>; } </script>
这段代码应该是CSS代码,但是是写在script内的,且使用了<%=***%>的赋值,它是如何获取值并转化为页面的CSS的?
type="text/plain"
这个是关键
你可以参考jquery的template相关函数实现,是完全一个道理。<script>
在html里默认的不可见元素,你可以把它看成一个普通的dom元素,在用document.getElementById('skinTemplate').innerHTML
获取它的内容后,将里面的<%=...%>
用正则替换成相应的值,然后将它set到一个style元素里,最后append到body里去。
这是一段模板引擎的模板, javascript根据ID取到这段模板的内容,就是上面<script>标签里的内容。
然后根据预设的变量去渲染模板,就是上面中的内容,渲染成常量。
至于是用作CSS还是普通的HTML,没人规定这个,看你需求,渲染完直接写到页面里。