2016-04-18 62 views
4

我是一个真正的jQuery newbee并发现这个脚本 - 它的伟大工程,但只有当我触摸屏幕(手机)......如何自动激活jQuery脚本

我正在寻找一种方法自动激活脚本...任何人都可以帮助我吗?

<script> 
    // changing the order of the sidebar so it goes after the content for mobile versions 

    jQuery(window).resize(function(){ 

     if (jQuery(window).width() < 480) 
     { 
      jQuery('.mid_grid_right').insertBefore('.mid_grid_left'); 
     } 

     if (jQuery(window).width() > 480) 
     { 
      jQuery('.mid_grid_left').insertBefore('.mid_grid_right'); 
     } 

     jQuery(window).height(); // New height 
     jQuery(window).width(); // New width 
    }); 
</script> 

回答

1

当你的DOM准备的回调函数时自动调用,所以你应该做的:

<script> 
    function resizeFn(){ 
     if (jQuery(window).width() < 480) { 
     jQuery('.mid_grid_right').insertBefore('.mid_grid_left'); 
     } 
     if (jQuery(window).width() > 480) { 
     jQuery('.mid_grid_left').insertBefore('.mid_grid_right'); 
     } 
     jQuery(window).height(); // New height 
     jQuery(window).width(); // New width 
    } 

    jQuery(window).resize(resizeFn); 
    jQuery(document).ready(resizeFn) ; 
</script> 
0

你可以做调整大小的逻辑到它自己的功能,然后wireup事件调用相同的功能:

<script> 
    // When your page is ready (and jQuery is loaded), call your function 
    $(function(){   
     resize(); 
    }); 
    // When the window is resized, call your function 
    $(window).resize(function(){ 
     resize(); 
    }); 
    // Define your function 
    function resize(){ 
     if ($(window).width() < 480) { 
      $('.mid_grid_right').insertBefore('.mid_grid_left'); 
     } 
     if ($(window).width() > 480){ 
      $('.mid_grid_left').insertBefore('.mid_grid_right'); 
     } 
     $(window).height(); 
     $(window).width(); 
    } 
</script> 
0

该代码位于resize事件的侦听器中。要使页面载入上运行相同的代码,只需为document.ready添加一个侦听器,并将引用传递给相同的函数。

function gripChange(){ 
    if (jQuery(window).width() < 480) 
    { 
     jQuery('.mid_grid_right').insertBefore('.mid_grid_left'); 
    } 
    if (jQuery(window).width() > 480) 
    { 
     jQuery('.mid_grid_left').insertBefore('.mid_grid_right'); 
    } 
    jQuery(window).height(); // New height 
    jQuery(window).width(); // New width 
} 

jQuery(window).resize(gripChange); 
jQuery(document).ready(gripChange); 
0

用jQuery准备好包裹整个块。 DOM没有按照你实现它的方式做好准备,浏览器甚至不知道“窗口”甚至代表什么。

此外,不要一再重复jQuery(窗口)以获得更快的响应。

<script> 
    // changing the order of the sidebar so it goes after the content for mobile versions 
    jQuery(document).ready(
     var $window = jQuery(window); 
     $window.resize(function(){ 

      if ($window.width() < 480) 
      { 
       jQuery('.mid_grid_right').insertBefore('.mid_grid_left'); 
      } 
      // if (jQuery(window).width() > 480) 
      else 
      { 
       jQuery('.mid_grid_left').insertBefore('.mid_grid_right'); 
      } 

      $window.height(); // New height 
      $window.width(); // New width 
     }); 
    }); 
</script>