简体   繁体   English

我的脚本运行完美,直到我将其包装在if(screen.width <980){}语句中以检查屏幕大小

[英]My script runs perfectly until I wrap it in this if (screen.width < 980) { } statement to check screen size

@John @约翰

Ok, I had the greater than sign mixed up. 好吧,我有大于号的混合。 The simple things....What I'm looking to do is have codeMagic() run on page load only if the browser.width() > 941px, if the page is resized < 941px stop codeMagic() from running. 简单的事情....我要做的是让codeMagic()在页面加载时运行,如果browser.width()> 941px,如果页面调整大小<941px停止codeMagic()运行。 If the page is again resized & the browser width is >= 941px turn codeMagic() on. 如果页面再次调整大小并且浏览器宽度> = 941px,则打开codeMagic()。 Then of course if the page loads less than 941px don't run codeMagic(), but keep the resizing awareness. 然后当然如果页面加载小于941px不运行codeMagic(),但保持调整大小意识。

Here is my example code: 这是我的示例代码:

CSS: CSS:

<style>
    body { margin: 0; }
    footer { padding: 10px; margin: 10px; height: 100%; } 
  </style>

HTML: HTML:

<div id="home">home!</div>
<footer>footer!</footer>

<script src='lib/js/vendor/jquery.js'></script>
<script src='../den.js'></script>

JS: JS:

jQuery( document ).ready(function($) { 
// set element height based on 'window height' - 'footer height' 

function codeMagic() {

    var docHeight = parseInt($( window ). height());     
    var footerHeight = parseInt($( 'footer' ).outerHeight( true ));
    var homeHeight = +docHeight - +footerHeight + 'px';

        $( 'body #home' ).height(homeHeight);
        console.log( homeHeight, footerHeight);         
};

if (jQuery(window).width() >= 941) {  

codeMagic(); // init codeMagic

//Set codeMagic to run on browser resize
$( window ).resize( function() { 

    codeMagic();

    });
   }
});

What is the proper way to do this? 这样做的正确方法是什么?

Your resize event never gets triggered if the browser is bigger than 941 px on DOM init because you didn't bind it than. 如果浏览器在DOM init上大于941 px ,则永远不会触发您的resize事件,因为您没有绑定它。 You need to change it like the following: 您需要像下面这样更改它:

if (jQuery(window).width() >= 941) {  
  codeMagic(); // init codeMagic
}


//afterwards bind to the resize event
$( window ).resize( function() { 
  //check size again
  if (jQuery(window).width() >= 941) {  
    codeMagic();
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM