【问题标题】:javascript android window.onorientationchange fires continuouslyjavascript android window.onorientationchange不断触发
【发布时间】:2011-11-02 05:27:36
【问题描述】:

我正在尝试检测移动设备上的方向变化,并在方向完成后触发一个函数,但函数内部的代码在 Android 中不断触发,我不知道为什么。这是我的代码:

var supportsOrientationChange = "onorientationchange" in window;
var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, 
   function() { alert ('orientation changed'); }, 
   false
);

有谁知道如何编写它以便在方向更改完成后只触发一次?

【问题讨论】:

    标签: javascript jquery android mobile


    【解决方案1】:

    我在我的应用程序中使用了解决方法。我为orientationchange 添加了一个事件监听器,然后设置了一个超时,这样orientationchange 就会发生,我可以获得一个新的width 值,它实际上反映了方向更改后的宽度。

    var device_width = 0;
    $(document).ready(function () {
        var oc_timer;
        $(window).bind('orientationchange', function () {
            clearTimeout(oc_timer);
            oc_timer = setTimeout(function () {
                device_width = $(window).width();
            }, 500);
        });
    });
    

    我不肯定这会解决您的连续触发功能问题,但这是我发现可行的解决方案。

    【讨论】:

      【解决方案2】:

      我找到了一种方法,以防其他人仍然遇到同样的问题,请查看:

      function onOrientationChange() {
          if (typeof(this.orientation) === "undefined"){
              if (window.orientation == -90 || window.orientation == 90) {
                  this.orientation = "landscape";
              } else {
                  this.orientation = "portrait";
              }
              // alert ("in 1");
              // you code here for change
          }
      
          if ((window.orientation == -90 || window.orientation == 90) && (this.orientation == "portrait")) {
              this.orientation = "landscape";
              // alert ("in 2");
              // you code here for change
          }
      
          if ((window.orientation == 0 || window.orientation == 180) && (this.orientation == "landscape")) {
              this.orientation = "portrait";
              // alert ("in 3");
              // you code here for change
          }
      }   
      

      【讨论】:

      • 注意此处代码中的标签,它们会被删除,最好使用空格进行缩进,因为它们在任何地方都是一致的。
      • 你是怎么调用这个函数的?您是否将其绑定到orientationchange 事件?或者只是通过 setTimeout 每 500 毫秒调用一次?
      【解决方案3】:

      针对不太详细的应用程序的简单解决方案

      //bind orientation change event
      $(window).bind("orientationchange", orientationChange);
      
      //later,
      
      function orientationChange(){
          //whatever needs to happen when it changes.
          alert("changed");
      }
      

      如果您需要传递信息,也可以使用 $.on()。

      在不支持它的浏览器中,该事件不会触发。然后,您可以编写自定义检测脚本作为备用,以在不支持 onorientationchange 的设备上发生方向更改时触发事件。

      【讨论】:

        猜你喜欢
        • 2011-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-21
        相关资源
        最近更新 更多