按下Tab键后,Firefox中的任何字符后文本框便会散焦

时间:2019-07-15 20:31:54

标签: javascript textbox focus

我正试图制作一个类似于CodePen和JSfiddle的浏览器内HTML编辑器。我进行了一项测试,允许选项卡不散焦编辑器。它工作正常,但在Firefox中除外。在Firefox中,在按下Tab键后才保持焦点,只是在下一次按键后失去焦点。

let textbox = document.getElementById("preview-textbox");//textbox used for inserting HTML into iframe
    textbox.value = "";

let iframe = document.querySelector("iframe");//used to render user's code

    textbox.addEventListener("input", (e)=>{//inserts html from textbox into the iframe
        iframe.src = "data:text/html," + encodeURI(textbox.value);
    });
    textbox.addEventListener("keydown", (e)=>{//allows indentation with 'tab'
        let cursor_position = textbox.selectionStart;
        let is_tab = e.keyCode || e.which;
        if(is_tab === 9){
            textbox.value = textbox.value.substr(0, cursor_position) + '\t' + textbox.value.substr(cursor_position, textbox.value.length);
            let focus_textbox = setInterval(()=>{
                                            textbox.focus();//refocuses textbox
                                            textbox.selectionEnd = ++cursor_position;//sets cursor position
                                            clearInterval(focus_textbox);}, 30);//clear setInterval
        } 


    });

0 个答案:

没有答案