使用焦点激活AppBar时显示软键盘会使内容跳回到顶部

时间:2015-11-25 02:37:57

标签: javascript html windows-phone winjs uwp

目前刚刚开始开发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(因为它消失了),将编辑器置于焦点,然后滚动回到之前的位置。这需要几秒钟的时间来执行,滚动太明显,无法成为可行的解决方案。

1 个答案:

答案 0 :(得分:0)

如果要将屏幕滚动到所选位置,则应计算坐标的offset,该坐标由于显示软键盘而移动。

这是我的Javascript代码:

(function(){     “使用严格”;

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