【问题标题】:Prevent Javascript from continuing a function if the screen is lower than 480 pixels如果屏幕低于 480 像素,则阻止 Javascript 继续执行功能
【发布时间】:2012-06-22 09:29:04
【问题描述】:

首先,我不是 javascript 专家。我正在疯狂地试图弄清楚如何有条件地执行某个 javascript。我正在使用 JQuery 将我的块绝对居中在浏览器页面中,但前提是屏幕尺寸大于 480 像素(换句话说,我不希望此脚本在智能手机上运行)。我正在使用 CSS 媒体查询来表明我的请求。问题是,这个脚本适用于所有智能手机、Safari 5+、IE10、Firefox 13。但它不适用于 IE6-9 和 Opera 12(据我了解,它们不支持转换)。谁能帮我弄清楚我做错了什么?如果有更好的方法来做到这一点? (我在 CSS 中尝试了 @media 查询,但无论如何脚本都会继续运行)...我非常感谢您的帮助。

    <script>
    if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
        // smartphone/iphone... maybe run some small-screen related dom scripting?
        event.preventDefault(); 
    } else{


        //Absolute Content Center
        function CenterItem(theItem){
            var winWidth=$(window).width();
            var winHeight=$(window).height();
            var windowCenter=winWidth/2;
            var itemCenter=$(theItem).width()/2;
            var theCenter=windowCenter-itemCenter;
            var windowMiddle=winHeight/2;
            var itemMiddle=$(theItem).height()/2;
            var theMiddle=windowMiddle-itemMiddle;
            if(winWidth>$(theItem).width()){ //horizontal
                $(theItem).css('left',theCenter);
            } else {
                $(theItem).css('left','0');
            }
            if(winHeight>$(theItem).height()){ //vertical
                $(theItem).css('top',theMiddle);
            } else {
                $(theItem).css('top','0');
            }
        }
        $(document).ready(function() {
            CenterItem('.content');
        });
        $(window).resize(function() {
            CenterItem('.content');
        });
    } //end of "else" (normal execution)

</script>

【问题讨论】:

    标签: javascript jquery css cross-platform media-queries


    【解决方案1】:

    你可以试试这个:-

    <script>
        var screenWidth = screen.width;
    
        if (screenWidth > 480 ) {
    
        //Absolute Content Center
        function CenterItem(theItem){
            var winWidth=$(window).width();
            var winHeight=$(window).height();
            var windowCenter=winWidth/2;
            var itemCenter=$(theItem).width()/2;
            var theCenter=windowCenter-itemCenter;
            var windowMiddle=winHeight/2;
            var itemMiddle=$(theItem).height()/2;
            var theMiddle=windowMiddle-itemMiddle;
            if(winWidth>$(theItem).width()){ //horizontal
                $(theItem).css('left',theCenter);
            } else {
                $(theItem).css('left','0');
            }
            if(winHeight>$(theItem).height()){ //vertical
                $(theItem).css('top',theMiddle);
            } else {
                $(theItem).css('top','0');
            }
        }
        $(document).ready(function() {
            CenterItem('.content');
        });
        $(window).resize(function() {
            CenterItem('.content');
        });
    }
    
    </script>
    

    【讨论】:

    • 非常感谢....您的解决方案确实有效,伙计 :) 它适用于 IE8 和 Opera 12,以及 iOS 5 和 WP7...谢谢,伙计 :)))跨度>
    【解决方案2】:

    在所有浏览器中获得精确的高度和宽度是非常重要的,因为 IE,但不用担心是所有浏览器的解决方案,包括 IE 6 到最新。

    以下是这 2 个功能:

         if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
            // smartphone/iphone... maybe run some small-screen related dom scripting?
            event.preventDefault(); 
        } else{
    
    
            //Absolute Content Center
    
            $(document).ready(function() {
                CenterItem('.content');
            });
            $(window).resize(function() {
                CenterItem('.content');
            });
        } //end of "else" (normal execution)
    
    
    
    function CenterItem(theItem){
                      var winWidth=getWindowWidth();
                      var winHeight=getWindowHeight();
                      var windowCenter=winWidth/2;
                      var itemCenter=$(theItem).width()/2;
                      var theCenter=windowCenter-itemCenter;
                      var windowMiddle=winHeight/2;
                      var itemMiddle=$(theItem).height()/2;
                      var theMiddle=windowMiddle-itemMiddle;
                      if(winWidth>$(theItem).width()){ //horizontal
                          $(theItem).css('left',theCenter);
                      } else {
                          $(theItem).css('left','0');
                      }
                      if(winHeight>$(theItem).height()){ //vertical
                          $(theItem).css('top',theMiddle);
                      } else {
                          $(theItem).css('top','0');
                      }
                  }
    
    function getWindowHeight() {
      var myHeight = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
    
        myHeight = window.innerHeight;
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    
        myHeight = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    
        myHeight = document.body.clientHeight;
      }
      return myHeight;
    }
    function getWindowWidth() {
      var myWidth = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
    
        myWidth = window.innerWidth;
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    
        myWidth = document.documentElement.clientWidth;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    
        myWidth = document.body.clientWidth;
      }
      return myWidth;
    }
    

    这将帮助您在任何浏览器中获得准确的高度,这样您就可以应用您的逻辑。希望对您有所帮助!!!

    【讨论】:

    • 感谢 Ishan,您的帮助... 正如我所说,我不是 javascript 专家。我只是在学习。那么我在哪里把你的代码放在我的脚本中呢?
    【解决方案3】:

    如果媒体查询不匹配,最简单的事情就是不附加事件处理程序。

    $.fn.extend({
        centerItem: function () {
            return this.each(function () {
                var $this   = $(this),
                    hCenter = ( $(window).width() - $this.width() ) / 2,
                    vCenter = ( $(window).height() - $this.height() ) / 2;
    
                $this.css({
                    left: hCenter > 0 ? hCenter : 0,
                    top:  vCenter > 0 ? vCenter : 0
                });
            });
        }
    });
    
    $(function() {
        var bigScreen = 'only screen and (max-device-width:800px) and (orientation: portrait)';
    
        if ( matchMedia(bigScreen).matches ) {
            $(window).resize(function() {
                $('.content').centerItem();
            });
        }
    });
    

    注意事项

    • $() 替换 $(document).ready()。见http://api.jquery.com/ready/
    • 按照惯例,只有对象构造函数以大写字母开头,因此您的 CenterItem() 函数实际上应该被称为 centerItem()
    • 我已经把你的函数变成了一个 jQuery 插件。如果您觉得这令人困惑,您当然可以继续使用您自己的实现。
    • .css() 函数可以接受一个对象参数,因此您可以一步设置多个 CSS 属性。
    • 我已使用三元运算符 (expression ? ifTrue : ifFalse) 来替换 if

    【讨论】:

    • 谢谢,Tomalak,但似乎代码有错误,因为我的控制台告诉我缺少预期的令牌')'...
    【解决方案4】:

    你可以的

    window.innerHeight
    window.innerWidth
    

    获取视口的尺寸。现在你可以这样做了:

    var width = window.innerWidth
    if (width > 480){
          /* do desktop stuff*/
    }
    

    作为替代方案,您可以选择 UserAgentString 和/或操作:

    window.navigator
    

    (more reliable Detect-script)

    但是,在某些情况下,任何一种尝试都可能失败。

    编辑:如果你发布你的 match-media 函数会很好。

    edit2:使用脚本进行正确的视口检测:https://stackoverflow.com/a/2035211/1047823

    然后修改你的代码:

    if ( getViewport()[0] < 480 ) {
            // smartphone/iphone... maybe run some small-screen related dom scripting?
            event.preventDefault(); 
        } else{
            // your desktop code
    }
    

    【讨论】:

    • 谢谢,Christoph,您的帮助...我尝试添加这些变量,但没有成功...有什么想法吗?
    • 这是我的 whichmobile();功能:function whichmobile() { var useragentstring=navigator.userAgent.toLowerCase(); alert(useragentstring); var mobilelist=new Array(("iphone os 6", "iphone os 5","ipad; cpu os 5","iphone","ipad","android 2","android", "windows phone os 7.5", "Windows nt 6.1", "blackberry","palmos", "nokia; lumia 800")); for (var device in mobilelist) { if (useragentstring.indexOf(mobilelist[device])&gt;=0) { return mobilelist[device]; break; } } } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2014-01-12
    相关资源
    最近更新 更多