gpt4 book ai didi

javascript - WKWebView - 防止用户文本选择触发的自动滚动

转载 作者:行者123 更新时间:2023-12-01 14:59:52 24 4
gpt4 key购买 nike

当用户执行点击并按住手势来选择一个单词,然后将他们的手指拖向屏幕的顶部或底部边缘时,页面会自动滚动以适应选择。

here is a short clip demonstrating it

我想在 WKWebView 中防止这种行为.

这是我到目前为止所尝试的:

bridge.js webview可以访问的文件:

var shouldAllowScrolling = true;

document.addEventListener('selectionchange', e => {
shouldAllowScrolling = getSelectedText().length === 0;
window.webkit.messageHandlers.selectionChangeHandler.postMessage(
{
shouldAllowScrolling: shouldAllowScrolling
});
console.log('allow scrolling = ', shouldAllowScrolling);
});

然后在 WKScriptMessageHandler执行:
public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
{
switch message.name
{
case "selectionChangeHandler":
let params = paramsDictionary(fromMessageBody: message.body)
let shouldEnableScrolling = params["shouldAllowScrolling"] as? Bool ?? true
cell?.webView.scrollView.isScrollEnabled = shouldEnableScrolling
cell?.webView.scrollView.isUserInteractionEnabled = shouldEnableScrolling // not together with the line above
default:
fatalError("\(#function): received undefined message handler name: \(message.name)")
}
}

同样,我尝试调用 preventDefault()函数直接在javascript文件中处理一堆事件,即 scrolltouchmove ,像这样:
document.addEventListener('touchmove', e => {
if (!shouldAllowScrolling) {
e.preventDefault()
}
}, {passive: false});

both methods successfully prevent scrolling when some text is selected but do not override the behavior described at the very top of my question.

我可以接受 Swift 和 JavaScript 或两者混合的解决方案。

最佳答案

我最终通过保存最后一个滚动位置并在适当时滚动到它来解决这个问题,如下所示:

var shouldAllowScrolling = true;
var lastSavedScrollLeft = 0;
var lastSavedScrollTop = 0;

function saveScrollPosition() {
lastSavedScrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
lastSavedScrollTop = window.pageYOffset || document.documentElement.scrollTop;
}

document.addEventListener('touchstart', e => {
saveScrollPosition();
});

document.addEventListener('touchend', () => {
// enable scrolling when the user lifts their finger, to allow scrolling while text selection is still present
shouldAllowScrolling = true;
});

document.addEventListener('scroll', e => {
if (!shouldAllowScrolling) {
window.scrollTo(lastSavedScrollLeft, lastSavedScrollTop);
}
});

document.addEventListener('selectionchange', e => {
shouldAllowScrolling = getSelectedText().length === 0;
});
如果有人可以提供更优雅的解决方案来完全阻止滚动,我很乐意接受它。
编辑:
此解决方案可能会导致轻微晃动/抖动。
这可以通过在 shouldAllowScrolling 时本地禁用滚动来解决设置为 false ,像这样:
webView.scrollView.isScrollEnabled = false

关于javascript - WKWebView - 防止用户文本选择触发的自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60548215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com