2014-12-02 64 views
1

我正在製作切換頁腳,它是width:100%;jQuery:切換頁腳,從#px調整爲100%寬度,並返回

我將它設置爲max-width:670px,我希望它在切換動畫之前擴展到100%的寬度。 這裏是我的codepen: http://codepen.io/GCW/pen/ZYbvPO

正如你所看到的,它的工作原理。但我必須在各種屏幕上設置maxWidth: '5000'以使其具有全寬。這樣,我的動畫就不流暢了,我的頁腳可以非常快地回到670px。我玩動畫時間,但我相信有更好的方法來做到這一點。 我想我的代碼對於這個簡單的動作也太長了。

我也試圖與var window_width = $(window).width()然後.animate({ maxWidth: window_width }..和它工作得很好,只是直到我調整我的窗口,因爲它有一個精確的寬度值,而不是百分比,所以它有一些固定的寬度。

+0

那麼確切的問題是什麼?你的動畫是不是流動的,因爲5000和670的巨大差距?那是對的嗎? – 2014-12-02 17:39:46

+0

對。我正在尋找一種方法來獲得100%的寬度沒有那個瘋狂的5000值 – GCW 2014-12-02 17:42:33

回答

2

您可以使用新的瀏覽器的CSS 100vw財產,但對於舊的瀏覽器可以使用jQuery來獲取窗口的寬度。以下是您的代碼,並在下方進行調整。

(function($) { 
    $(document).ready(function() { 

     $('.nav-toggle').click(function(){ 

      var content_selector = $(this).attr('href'); 
      var my_switch = $(this); 

      //Added variable 
      var viewPortWidth = $(window).outerWidth(); 

      if (my_switch.hasClass('close_toggle')) { 
        $(content_selector).slideToggle(function(){ 
         $('.collapsing_footer').animate({ 
         maxWidth: '670'}, 400); 
         my_switch.removeClass('close_toggle'); 
        }); 

        //Remove resize event bind 
        jQuery(window).unbind(); 

      } else { 


       //on resize adjust the max width 
       jQuery(window).resize(function() { 
        //reset viewport width variable to current 
        viewPortWidth = $(window).outerWidth(); 
        $('.collapsing_footer').css({ maxWidth : viewPortWidth }); 
        console.log("here"); 
       }); 


       $('.collapsing_footer').animate({ maxWidth: viewPortWidth }, 600, 

       function() { 
        $(content_selector).slideToggle(
         function(){ 
         my_switch.toggleClass('close_toggle'); 
         } 
        ); 

        $('body').animate({ scrollTop: 999999 }, 700); 

       }); 

      } 

     }); 

    }); 
    })(jQuery); 

如果你有瀏覽器版本檢測,我建議你用它來填充變量viewPortWidth。這裏是關於vw css的文章,也包含瀏覽器支持。 http://css-tricks.com/viewport-sized-typography/

+0

正確,但是如果在1000px寬度的情況下切換菜單,例如,您將瀏覽器調整爲1500px,菜單保留在1000px,因爲存儲的viewPortWidth的值 – GCW 2014-12-02 18:20:27

+0

這是正確的,不適合用於彌補瀏覽器調整大小。 – 2014-12-02 18:21:44

+1

我添加了一個窗口重新大小事件,它現在可以調整瀏覽器調整大小時的最大值。當菜單未打開時,它也會清除該事件,以防止670最大變化。 – 2014-12-02 18:28:27

1

你可以嘗試使用視口寬度:

maxWidth: '100vw' 
+0

哦,是的!有用! :) 謝謝! – GCW 2014-12-02 17:48:20