Android WebView 获取html页面聚焦input在页面的位置,实现代码如下:文章来源:https://www.toymoban.com/news/detail-616224.html
@SuppressLint("SetJavaScriptEnabled")
private void HTMLFocusLocation(Context context) {
String js = "(function () {" +
"var activeElement = document.activeElement;" +
"var rect = activeElement.getBoundingClientRect();" +
"return {'left': rect.left, 'top': rect.top, 'width': rect.width, 'height': rect.height}" + // 返回json对象
"})();";
// 设置支持 javaScript
mWebView.getSettings().setJavaScriptEnabled(true);
// 执行js获取聚焦位置的坐标
mWebView.evaluateJavascript(js, new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
Log.d(TAG, "onReceiveValue: " + value);
try {
JSONObject object = new JSONObject(value);
double left = object.optDouble("left");
double top = object.optDouble("top");
double width = object.optDouble("width");
double height = object.optDouble("height");
Log.d(TAG, "onReceiveValue left: " + left + ", top: " + top + ", width: " + width + ", height: " + height);
// 返回的数据是dp, 用的时候需要转换成像素px
float density = context.getResources().getDisplayMetrics().density;
Log.d(TAG, "onReceiveValue density: " + density);
int leftPixel = (int) (left * density);
int topPixel = (int) (top * density);
int widthPixel = (int) (width * density);
int heightPixel = (int) (height * density);
Log.d(TAG, "onReceiveValue left: " + leftPixel + ", top: " + topPixel + ", width: " + widthPixel + ", height: " + heightPixel);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
注意:文章来源地址https://www.toymoban.com/news/detail-616224.html
- WebView 要设置setJavaScriptEnabled支持JavaScript调用
- 返回的数值是以dp为单位,使用时需要转换为像素px
到了这里,关于Android WebView 获取html页面聚焦input在页面的位置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!