Webview嵌套在NestedScrollView中含锚点问题

3

我有一个包含WebView的NestedScrollView。 WebView包含一个HTML文件,其中包含锚点,这些锚点链接到相同的文件但不同的位置(想象一下“菜单”和“内容”容器。当您单击菜单项时,“内容”中对应的部分应出现在屏幕上)。

<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/svNested"
    android:layout_height="match_parent"
    tools:showIn="@layout/activity_single"
    android:background="@color/colorPrimary">

        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

</android.support.v4.widget.NestedScrollView>

加载数据:

webView?.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null)

问题在于这些锚点的效果与预期不符。

你找到解决方案了吗? - Mr. Robot
不好意思,但那是三年前的事了。 - P. Savrov
我已经在这里回答了这个问题:https://dev59.com/Sb3pa4cB1Zd3GeqPjraI#72991301 - Pradyuman Kaushal
1个回答

1

我通过使用JavaScript计算锚点的位置并在调用自定义URL并使用WebViewClient捕获它时,通过编程方式滚动NestedScrollView来使锚点起作用。以下是一些代码片段(我只垂直滚动,但您可以轻松地将其扩展为水平滚动):

在Activity或Fragment中(引用了NestedScrollViewWebView):

webView.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            if(url.startsWith("scrollto")) {
                val offset = url.replace("scrollto://", "");
                val offsetInt = MapUtils.getDensityIndependentPixels(offset.toFloat(), requireContext()).toInt()
                (webView.parent as NestedScrollView).scrollTo(0, offsetInt)
               return true
            }
            return false
        }
    }

//We need this, because the measured pixels in the WebView don't use density of the screen
fun getDensityIndependentPixels(pixels: Float, context: Context): Float {
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        pixels,
        context.resources.displayMetrics
    )
}

在你的 Javascript 中(或者 HTML 的 <script> 标签中):
function getOffset(el) {
    const rect = el.getBoundingClientRect();
    return {
        top: rect.top + window.pageYOffset,
        left: rect.left + window.pageXOffset
    };
}
                    
function makeItScroll(id) {
     var element = document.getElementById(id)
     var offsetTop = getOffset(element).top
     window.location = "scrollto://"+offsetTop
}

最后,在HTML中使用它,像这样:

你想要滚动到的 div<div id="here">...</div>

滚动到那里的 a<a href="javascript:makeItScroll('here');">...</a>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接