Adding CodeMirror to Shadow Dom of Custom Element?

纵饮孤独 提交于 2019-12-04 05:16:21

问题


I'd like to dynamically create a CodeMirror instance inside a Custom Element and have it live inside the element's Shadow DOM. For example:

<code-mirror>foo</code-mirror>
<script>
window.customElements.define('code-mirror', class extends HTMLElement {
    constructor() {
        super();
        let shadowRoot = this.attachShadow({mode: 'open'});
    }

    connectedCallback() {
        this.cm = CodeMirror(this.shadowRoot, {lineNumbers: true});
    }
});
</script>

This "works" but the layout is all wrong.. margin-left gets set to the width of the window, line numbers aren't displayed correctly and the selection logic is off by a few lines vertically.

Here's a jsfiddle demonstrating the layout issue: link

Suggestions?


回答1:


Import CodeMirror's stylesheet inside the shadow DOM with @import url:

constructor() {
    super();
    let shadowRoot = this.attachShadow({ mode: 'open' });
    shadowRoot.innerHTML = `
        <style>
           @import url(https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.24.2/codemirror.min.css)
        </style>`         
}


来源:https://stackoverflow.com/questions/42757381/adding-codemirror-to-shadow-dom-of-custom-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!