如何在编辑器里添加CSS或JS代码

//编辑器里代码模式下的代码
<scripttype="text/javascript">
//my code....
</script>
//编辑器里可视化模式下的代码
<scripttype="text/javascript">
// <![CDATA[
//my code....
// ]]>
</script>

  

最近在使用Wordpress做一个网站项目,需要在后台编辑器里添加自定义的JS脚本和CSS

在编辑器里添加好后,发现在浏览器里JS脚本执行有问题并且CSS的脚本直接被WordPress保存的时候过滤掉了
经过排查发现原因是Wordpress默认的TinyMCE在从代码模式切换到可视化模式的时候对脚本时行了处理
更无耻的是CSS的脚本直接被删除了
 
wiki CDATA上的说明

CDATA sections in XHTML documents are liable to be parsed differently by web browsers if they render the document as HTML, since HTML parsers do not recognise the CDATA start and end markers, nor do they recognise HTML entity references such as &lt; within <script> tags. This can cause rendering problems in web browsers and can lead to cross-site scripting vulnerabilities if used to display data from untrusted sources, since the two kinds of parser will disagree on where the CDATA section ends.

Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline <script> and <style> elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:

 
所以正确的写法应该是这样子的
//JavaScript example:
<script type="text/javascript">
//<![CDATA[
//mycode
document.write("<");
//]]>
</script>
 
//CSS example:
<style type="text/css">
/*<![CDATA[*/
//my code
body { background-image: url("marble.png?width=300&height=300")}
/*]]>*/
</style>
 
 
参考:





原文地址:https://www.cnblogs.com/huangtailang/p/93d806b642106d04f173ee15ad6bb1a0.html