用Javascript显示动态代码段

时间:2018-08-15 15:04:34

标签: javascript code-snippets google-code-prettify

我正在编写JS函数:

showCodeSnippet(fileName)
Input: Local File Name 
Output: Display Code in HTML

我知道一些安全限制,这些限制限制了浏览器中对本地文件的访问,但是设法创建了一种解决方法。

请考虑以下代码(适用于Firefox 57.0,64位):

<html>
<head>
<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
</head>

<body>

<script>

async function showCodeSnippet(fileName) 
{        
    const response = await fetch(fileName);
    const text = await response.text(); 

    var parser = new DOMParser();
    var domString = "<pre class=\"prettyprint\">" + text + "</pre>";
    var html = parser.parseFromString(domString, 'text/html');  
    document.body.append(html.body.firstChild);
}
</script>


<script>
showCodeSnippet('Code.txt');
</script>

</body>
</html>

Code.txt包含一些示例C ++代码:

using namespace std;
int main()
{
     int n;
     cout << "Enter an integer: ";
     cin >> n;

     if ( n % 2 == 0)
            cout << n << " is even.";
     else
            cout << n << " is odd.";
     return 0;
}

输出HTML页面: enter image description here

问题陈述:

语法突出显示不起作用。

尝试:

  • Google代码修饰
  • 棱镜荧光笔

如果荧光代码位于HTML标记下,则这些荧光笔可以正常工作。

有人可以提供任何提示-这个问题的根本原因,还是我应该以其他任何方式实现这种功能?

谢谢

1 个答案:

答案 0 :(得分:1)

我发现Chrome有所不同。当我使用Firefox时,我会遇到与您相同的问题。等等,我会检查一些事情:)

在添加后添加import xlsxwriter as xlwr xlwrwb = xlwr.Workbook('c:\myworkbook.xlsx') xlwrsheet = xlwrwb.get_worksheet_by_name(sheet.title) rrow = 10 ccol = 8 ttxt = "This is an example textbox created by OpenPyXL." xlwropts = { 'width': 400, 'height':200, 'fill': {'color': '#EEE8AA'}, 'align': {'vertical': 'middle', 'horizontal': 'center'}, 'font': {'bold': True, 'name': 'Arial', 'size': 16, 'color':'orange'}, } xlwrsheet.insert_textbox(rrow,ccol,ttxt, xlwropts) xlwrwb.close() 时,漂亮的字体也将在FireFox中使用。代码(:

似乎不支持FireFox自动重绘