render设置样式
时间: 2023-07-04 21:25:49 浏览: 40
如果你想设置渲染的样式,可以在调用 `render` 函数时传入一个包含样式属性的对象作为第二个参数,例如:
```javascript
const marked = require('marked');
const markdown = '# Hello, world!\n\nThis is **bold** and this is *italic*.';
const style = {
backgroundColor: '#f5f5f5',
color: '#333',
padding: '10px'
};
const html = marked(markdown);
const renderedHtml = marked(markdown, { sanitize: true });
document.getElementById('markdown').innerHTML = html;
document.getElementById('renderedMarkdown').innerHTML = renderedHtml;
document.getElementById('renderedMarkdownWithStyle').innerHTML = marked(markdown, { sanitize: true, renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, smartLists: true, smartypants: false, highlight: function (code, lang) { return require('highlight.js').highlightAuto(code).value } }).replace(/<pre><code/g, '<pre style="' + styleToString(style) + '"><code');
function styleToString(style) {
return Object.keys(style).map(key => `${key}:${style[key]}`).join(';');
}
```
这里使用了 `marked` 库来将 Markdown 转换为 HTML,然后通过设置 `sanitize` 选项为 `true` 来防止 XSS 攻击。最后通过创建一个新的 `marked.Renderer` 对象并将其传递给 `marked` 函数来自定义渲染器,然后将样式对象转换为字符串并添加到 `<pre>` 标签的 `style` 属性中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)