当 AppBar 处于活动状态时显示软键盘使用焦点使内容跳回顶部

Show soft keyboard when AppBar is active using focus makes the content jump back to the top

目前刚开始开发 UWP WinJS 应用程序,在 Windows 10 Mobile 上测试。

我有一个 appbar 和一个 contenteditable div - 如果我按下 appbar 上的按钮将内容区域中的某些单词加粗,div 会将其加粗,但也会完全跳转当调用 editor.focus() 时到顶部。我希望它保持在当前位置。

我想做的是即使按下 AppBar 上的按钮也能显示键盘。 (如果没有 editor.focus(),键盘会在点击按钮时消失。)不幸的是,有了这行额外的代码,我遇到了上述滚动问题。

<div id="editor" contenteditable="true">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam tristique convallis aliquet. Proin ac urna ut diam luctus facilisis vel in ligula. Morbi porta volutpat est eget semper. Sed elementum tincidunt libero. Cras a felis leo. Fusce lacinia turpis vel turpis facilisis sollicitudin. Suspendisse blandit, nisi gravida fermentum placerat, velit ipsum volutpat mi, ut finibus enim mauris at massa. Etiam placerat et mi eget iaculis. Aliquam et semper nisl. Integer id magna non sapien tempus suscipit at eget sem. Integer quam risus, placerat sit amet iaculis ac, ultrices non diam. Aliquam at convallis velit, vitae iaculis lectus. Morbi non orci eget mi placerat aliquet. Sed at neque a eros efficitur egestas. Donec sed luctus leo, ac ullamcorper dui.

    Nullam volutpat ultricies leo, ut congue risus egestas euismod. Suspendisse nisi ligula, volutpat id tempor convallis, facilisis in justo. Nulla porta neque eget ante tincidunt pellentesque. Integer felis libero, rutrum eu interdum eu, finibus a felis. Vestibulum vel est dictum, tempor ex vel, facilisis lorem. Nulla facilisi. Nulla ut ornare tortor, vitae blandit augue. Quisque imperdiet pretium turpis, ac fermentum diam imperdiet vitae. Pellentesque vel mollis odio. Quisque tempus eget neque non pretium.

    Cras eu velit sit amet dolor pulvinar ultricies at id lectus. Suspendisse quis metus sem. Etiam lectus mauris, lobortis volutpat consectetur at, sodales in nisl. Fusce euismod magna in leo tempor, quis bibendum leo gravida. Nulla varius velit vel ultrices sollicitudin. Morbi at odio efficitur, iaculis odio ut, auctor mauris. Phasellus nec lacus arcu. Duis porttitor, urna sit amet tempor dapibus, velit libero malesuada erat, eget pulvinar velit quam id leo. Quisque vulputate vehicula ante, vel condimentum dui consectetur eget.

    Curabitur lobortis porta justo quis pulvinar. Aliquam quam nisl, aliquam vel risus et, semper molestie nulla. Aenean mollis facilisis odio vel convallis. Suspendisse vestibulum nec sapien ut pretium. Duis vehicula, mi sed rutrum luctus, odio magna hendrerit nisl, laoreet eleifend augue neque vestibulum dui. Proin vitae metus convallis, condimentum enim in, volutpat nisl. Aliquam at est id felis placerat fermentum. Duis suscipit commodo convallis. Aliquam imperdiet mollis tortor, sit amet placerat tellus malesuada in. Nunc fringilla sem lorem, nec efficitur purus lobortis mollis. Duis non eros aliquam, luctus libero sed, ullamcorper odio.

    Fusce orci est, rutrum non urna a, finibus suscipit dolor. Mauris suscipit mi ut dolor cursus, quis laoreet est porta. Etiam bibendum fringilla turpis et sagittis. Aenean vehicula maximus dui ut pretium. Vestibulum iaculis id sapien nec condimentum. Donec a aliquet enim. Donec non mauris convallis, tincidunt elit sit amet, ultrices nulla. Duis vel auctor nisl, vitae ultrices mi. Suspendisse potenti. Vivamus sit amet lacus urna. Fusce a sagittis risus. Cras facilisis porta purus, vitae scelerisque mauris vehicula eu. 
</div>

<div data-win-control="WinJS.UI.AppBar" id="appBar" data-win-options="{placement: 'bottom', sticky: 'true'}" style="background-color: #e6e6e6;">       
        <button  data-win-control="WinJS.UI.AppBarCommand" data-win-options="{id: 'boldBtn', icon: 'bold', section:'selection', tooltip:'bold'}"></button>
</div>

Javascript:

element.querySelector("#boldBtn").addEventListener("click", toggleBold, false);

function toggleBold() {
    document.execCommand('bold', false, null);
    editor.focus();   // this will cause the div to jump back to the top if it's not already at the top
}

尝试使用 tryShow() 的另一种解决方案来检测键盘何时将被隐藏。一旦检测到,强制键盘出现。此外,显示 AppBar(因为它消失了),将编辑器放在焦点上,然后滚动回您之前所在的位置。这需要几秒钟的时间来执行,而且滚动太明显,不是一个可行的解决方案。

如果你想将屏幕滚动到你选择的位置,你应该计算坐标offset,这是由于软键盘的显示而移动的。

这是我的 Javascript 代码:

(函数(){ "use strict";

var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;

var userHeight, cursorY0, range;

app.onactivated = function (args) {
    if (args.detail.kind === activation.ActivationKind.launch) {
        if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
            // TODO: This application has been newly launched. Initialize your application here.
        } else {
            // TODO: This application was suspended and then terminated.
            // To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
        }
        args.setPromise(WinJS.UI.processAll().done(
            function () {



                //var editor = document.getElementById("editor");
                //editor.addEventListener("click", toggleBold, false);
                var button = document.getElementById("boldBtn");
                var text = document.getElementById("editor");
                var oRange = document.createRange();
                button.addEventListener("click", toggleBold, false);
                text.addEventListener('mouseup',function(e){

                    if (window.getSelection) {
                        var selection = window.getSelection();
                    } else if (document.selection) {
                        var selection = document.selection.createRange();
                    }
                    range = selection.getRangeAt(0);
                    cursorY0 = window.event.pageY;
                    console.log(cursorY0);
                })
                /*text.addEventListener("click", function () {
                    cursorY0 = window.event.pageY;
                    console.log(cursorY0);
                }, false);*/
                //console.log(window.innerHeight);
                userHeight = window.innerHeight;
            })
            );
    }
};

app.oncheckpoint = function (args) {
    // TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here.
    // You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension.
    // If you need to complete an asynchronous operation before your application is suspended, call args.setPromise().
};

function toggleBold() {
    var text = document.getElementById("editor");
    //Array.prototype.slice.apply(document.querySelectorAll("b")).forEach(function (b) {
    //    b.parentNode.replaceChild(b.firstChild, b);
    //});

    text.focus();
    var currentHeight = window.innerHeight;
    var cursorY1 = window.event.pageY;
    if (cursorY1 > currentHeight) {
        window.scrollTo(0, currentHeight - (cursorY1 - cursorY0));
    }

    var selectionContents = range.extractContents();
    var boldDom = document.createElement("b");

    boldDom.appendChild(selectionContents);
    range.insertNode(boldDom);


}

app.start();
})();

这是一个非JQuery的方法,我想你也可以引入一个JQuery包,并使用这里的method来计算offset