gpt4 book ai didi

javascript - WKWebView - 更改视口(viewport)?

转载 作者:行者123 更新时间:2023-11-28 19:59:20 24 4
gpt4 key购买 nike

我目前正在运行以下代码来设置我的 WKWebView 的视口(viewport):

NSString* viewPortjs = [NSString stringWithFormat:@"document.querySelector('meta[name=viewport]').setAttribute('content', 'width=%dpx;', false);", (int) webView.frame.size.width];
[webView evaluateJavaScript:viewPortjs completionHandler:nil];

我可以看到,如果代码找到选择器 viewport,它会正确设置它,但我想添加将此行添加到 DOM 的功能(如果它不存在)。说到 Javascript,我是个菜鸟,所以我不确定如何更改此代码以处理如果该选择器不存在并添加它的情况。谁能帮我吗?谢谢!

最佳答案

这是将完成您想要的 javascript:

var myCustomViewport = 'width=320px';
var viewportElement = document.querySelector('meta[name=viewport]');
if (viewportElement) {
viewportElement.content = myCustomViewport;
} else {
viewportElement = document.createElement('meta');
viewportElement.name = 'viewport';
viewportElement.content = myCustomViewport;
document.getElementsByTagName('head')[0].appendChild(viewportElement);
}

对于您的用例:

NSString* viewPortjs = [NSString stringWithFormat:@"var myCustomViewport = 'width=%dpx'; var viewportElement = document.querySelector('meta[name=viewport]');if (viewportElement) {viewportElement.content = myCustomViewport;} else {viewportElement = document.createElement('meta'); viewportElement.name = 'viewport'; viewportElement.content = myCustomViewport; document.getElementsByTagName('head')[0].appendChild(viewportElement);}", (int) webView.frame.size.width];

关于javascript - WKWebView - 更改视口(viewport)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24898507/

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