Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="g-container" contenteditable>这是 Web 云文档的一段内容,如果直接编辑,可以编辑成功。如果使用控制台修改,数据将会被恢复。</div>
              
            
!

CSS

              
                html, body {
    width: 100%;
    height: 100%;
    display: flex;
}
#g-container {
    position: relative;
    top: 100px;
    margin: auto;
    width: 400px;
    padding: 20px;
    line-height: 2;
    border: 2px dashed #999;
    
}
              
            
!

JS

              
                const targetElement = document.getElementById("g-container");
// 记录初始数据
let cacheInitData = '';
// 数据复位标志位
let data_fixed_flag = false; 
// 复位缓存对象
let cacheObservingObject = null;
let cacheContainer = null;
let cacheData = '';

function eventBind() {
    targetElement.addEventListener('focus', (e) => {
        console.log('focus', document.activeElement);
        // console.log('Target Focus!'); 
        // console.log('data_fixed_flag', data_fixed_flag);
        // console.log('cacheData', cacheData); 
        // console.log('cacheContainer', cacheContainer); 
        // console.log('cacheObservingObject', cacheObservingObject); 
        
        if (data_fixed_flag) {
            cacheContainer.innerText = cacheData;
            cacheObservingObject.disconnect();
            observeElementChanges(targetElement);
            
            data_fixed_flag = false;
        }
    });
    
    targetElement.addEventListener('blur', (e) => {
        console.log('blur', document.activeElement);
    });
    targetElement.addEventListener('paste', (e) => {
        console.log('paste', document.activeElement);
    });
    targetElement.addEventListener('onContextMenu', (e) => {
        console.log('onContextMenu', document.activeElement);
    });
}

function observeElementChanges(element) {
    const changes = []; // 存储变化的数组
    const targetElementCache = element.innerText;

    // 缓存每次的初始数据
    cacheInitData = targetElementCache;
    
    // 创建 MutationObserver 实例
    const observer = new MutationObserver((mutationsList, observer) => {
        // console.log('mutationsList', mutationsList);
        // 检查当前是否存在焦点
        // const hasFocus = targetElement === document.activeElement;
        mutationsList.forEach((mutation) => {
            // console.log('observer', observer);
            const { type, target, addedNodes, removedNodes } = mutation;
            let realtimeText = "";
            
            if (type === "characterData") {
                realtimeText = target.data;
            }
            
            const change = {
                type,
                target,
                addedNodes: [...addedNodes],
                removedNodes: [...removedNodes],
                realtimeText,
                activeElement: document.activeElement
            };
            changes.push(change);
        });
        console.log("changes", changes);
        
        let isFixed = false;
        let container = null;
        
        for (let i = changes.length - 1; i >= 0; i--) {
            const item = changes[i];
            // console.log('i', i);
            if (item.activeElement === element) {
                if (isFixed) {
                    cacheData = item.realtimeText;
                }
                break;
            } else {
                if (!isFixed) {
                    isFixed = true;
                    container = item.target.nodeType === 3 ? item.target.parentElement : item.target;
                    cacheContainer = container;
                    data_fixed_flag = true;
                }
            }
        }
        
        if (data_fixed_flag && cacheData === '') {
            cacheData = cacheInitData;
        }
        
        cacheObservingObject = observer;
    });

    // 配置 MutationObserver
    const config = { childList: true, subtree: true, characterData: true };

    // 开始观察元素的变化
    observer.observe(element, config);
    eventBind();
    
    // 返回停止观察并返回变化数组的函数
    return () => {
        observer.disconnect();
        return changes;
    };
}

observeElementChanges(targetElement);

              
            
!
999px

Console