编程语言
首页 > 编程语言> > 如果屏幕低于480像素,则阻止Javascript继续执行功能

如果屏幕低于480像素,则阻止Javascript继续执行功能

作者:互联网

首先,我不是一个JavaScript专家.我试图弄清楚如何对某个javascript进行条件执行,我会发疯的.我正在使用JQuery绝对将我的块放在浏览器页面中,但前提是屏幕大小大于480px(换句话说,我不希望这个脚本在智能手机上运行).我正在使用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>

解决方法:

你可以试试这个: –

<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>

标签:jquery,javascript,css3,cross-platform,media-queries
来源: https://codeday.me/bug/20190613/1232847.html