如何在uiwebview中处理Javascript onorientationchange事件
当通过iPhone中的如何在uiwebview中处理Javascript onorientationchange事件,javascript,ios,uiwebview,dom-events,orientation,Javascript,Ios,Uiwebview,Dom Events,Orientation,当通过iPhone中的uiwebview访问时,任何人都可以帮助我如何处理Javascript中的方向更改事件 我试图捕获Javascript的onorientationchange事件。我尝试了以下代码: <style type="text/css" media="only screen and (max-device-width: 480px)"> .portrait { width: 300px;
uiwebview
访问时,任何人都可以帮助我如何处理Javascript中的方向更改事件
我试图捕获Javascript的onorientationchange
事件。我尝试了以下代码:
<style type="text/css" media="only screen and (max-device-width: 480px)">
.portrait
{
width: 300px;
padding: 0 15px 0 5px;
}
.landscape
{
width: 460px;
padding: 0 15px 0 5px;
}
</style>
<script type="text/javascript">
window.onload = orientationchange;
window.onorientationchange = orientationchange;
function orientationchange() {
if (window.orientation == 90
|| window.orientation == -90) {
document.getElementById('contents').className = 'landscape';
}
else {
document.getElementById('contents').className = 'portrait';
}
}
</script>
// and I have a div inside html
<div id="contents">
my contents and description... e.t.c, and e.t.c...
</div>
.肖像
{
宽度:300px;
填充:0 15px 0 5px;
}
景观
{
宽度:460px;
填充:0 15px 0 5px;
}
window.onload=方向更改;
window.onorientationchange=方向更改;
函数方向更改(){
如果(窗口方向==90
||window.orientation==-90){
document.getElementById('contents')。className='scape';
}
否则{
document.getElementById('contents')。className='rapital';
}
}
//我在html中有一个div
我的内容和描述。。。e、 t.c.和e.t.c。。。
它在safari中运行良好,但当我使用uiwebview
访问页面时,没有捕获方向更改事件,无法实现我想要的功能。我想向您指出,在被接受的答案正下方的答案确实向您的问题致敬:处理应用程序代码中的方向更改,并使用javascript注入更改。我引用这句话是希望作者不会介意:
“第二个问题的答案是在UIWebView中未调用onorientationchange处理程序:
我注意到window.orientation属性无法正常工作,并且window.onorientationchange处理程序无法调用。大多数应用程序都存在此问题。可以通过设置window.orientation属性并在视图控制器的willRotateToInterfaceOrientation方法中调用window.onorientationchange来解决此问题N您的UIWebView:“谢谢您
另一种书写方式是:
var onorientationchange = function() {
document.getElementById('contents').className =
Math.abs(window.orientation == 90)? "landscape" : "portrait";
}
window.onload = function() {
window.onorientationchange = window.onorientationchange
}
将其放入
viewDidLoad
:
[[UIDevice currentDevice]beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasOrientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil];
- (void)hasOrientationChanged:(NSNotification *)notification {
UIDeviceOrientation currentOrientation;
currentOrientation = [[UIDevice currentDevice] orientation];
if(currentOrientation == UIDeviceOrientationLandscapeLeft){
NSLog(@"left");
}
if(currentOrientation == UIDeviceOrientationLandscapeRight){
NSLog(@"right");
}
}
现在,您可以使用正确的方向调用您的webview:)我不需要本地资源,我只想在我的html的javascriptI中捕获方向更改事件。我添加了我试图向您展示的帖子中的一段引用,但未成功。这实际上是你所说的问题;我的问题解决了。但在应用程序中使用支持方向的html页面是很奇怪的。不客气。是的,不应该是这样,但这是一个很好的解决此错误的方法。它看起来不错,我稍后会检查它并让您知道它是否有效。谢谢您的回答,但代码中有一个parens错误。你想要Math.abs(window.orientation)==90,而不是比较的abs…是的,它在应用程序中是正确的。但是我怎么能在我的html页面中知道呢?