jQuery检测页面大小调整或平板电脑&移动设备

时间:2013-07-15 20:58:17

标签: jquery

我在我的网站上创建了一个断点,因此它可以响应平板电脑和移动设备。一切顺利,但我想从底部移动一段内容并将其附加到导航下。

我有一个简单的两列布局右列和左列。 HTML的部分位于右列。我需要检测屏幕尺寸何时达到或低于558px然后移动。

HTML:

<div class="main wrapper">
    <div class="content-left"></div>
    <div class="content-right">
        // three divs containing awesome content
    </div>
</div>

jQuery:

 <script>
    var windowsize = $(window).width();

   if (windowsize < 559) {
   //if the window is less than 559px wide then prepend the following
   console.log('Window resized!!!');
   $(".now-playing-title, h1.now-playing-title, .live-now-block, .now-playing").prependTo('.content-left'); 
}

</script>

工作soluntion:我使用了.insertBefore()而不是.preprend()(它将所有内容移动到了left-left div中)并将其全部用document.ready()包装起来,以便在页面完全加载后触发。

 <script>
    $(document).ready(function() {

    var windowsize = $(window).width();

    if (windowsize < 559) {
    //if the window is less than 559px wide then append NowPlaying
    console.log('Window resized!!!');
    $(".now-playing-title, h1.now-playing-title, .live-now-block, .now-playing").insertBefore('.content-left'); 
    }    
    });
</script>

2 个答案:

答案 0 :(得分:1)

这不应该在javascript中完成。

您可以使用css媒体查询。

@media screen and (max-width: 558px) {
  ... do your thing
}

阅读this

答案 1 :(得分:-2)

http://api.jquery.com/resize/

$(window).resize(function() {
   if ($('.content-left').is(':empty') && $(window).width()  <= 559){

   console.log('Window resized!!!');
   $(".now-playing-title, h1.now-playing-title, .live-now-block, .now-playing").prependTo('.content-left');
   }
});
相关问题