2017-10-18 41 views
1

的準確寬度I有如下的腳本:塊現在的位置是固定下面瀏覽器

$(window).resize(function(){ 
if ($(window).width() >= 992){ 

    var windw = this; 

$.fn.followTo = function (pos) { 
var $this = this, 
    $window = $(windw); 

$window.scroll(function(e){ 
    if ($window.scrollTop() > pos){ 
     $this.css({ 
      position: 'static', 
      top: pos, 
      marginTop: 100 


     }); 
    } 
    else { 
     $this.css({ 
      position: 'fixed', 
      top: 100 
     }); 
    } 

}); 
}; 


$('#bgForm').followTo(1550);  



} 
}); 

我想阻斷時瀏覽器的尺寸低於992px固定的位置。我怎樣才能使用我的腳本來做到這一點? 我嘗試使用此代碼,但隨後元素停在位置上。 謝謝!

+0

我已更新我的代碼。請檢查 – Steve

+0

你能寫嗎?因爲我不完全知道你的意思。 – Steve

+0

是否有你正在使用JavaScript的特定原因? – scooterlord

回答

0

由於@designedbyscott說,我認爲媒體查詢是最簡單的解決方案,但既然你問你的JS腳本,這裏是剛剛創建了一個函數來檢查窗口寬度和應用的簡化版本你的位置會相應改變。它被稱爲加載,調整大小和滾動,雖然你可以決定什麼是最適合你的。將「your-element」更改爲您要定位的元素。

function positionFix() { 
    element = $('.your-element'); 
    width = $(window).width(); 
    scroll = $(window).scrollTop(); 
    if (width >= 992 || scroll > 1550) { 
    element.css('position','static'); 
    element.css('margin-top','100px'); 
    } else { 
    element.css('position','fixed'); 
    element.css('top','100'); 
    element.css('margin-top','0'); 
    } 
} 
window.addEventListener("load", positionFix); 
window.addEventListener("resize", positionFix); 
window.addEventListener("scroll", positionFix); 
+0

但在我的代碼中,這個元素停在精確的位置上,現在滾動到頁面結尾處不停。 – Steve

+0

你能解釋一下「停在準確的位置」是什麼意思嗎?或者發佈小提琴 – Tom

+0

看看我的代碼,有$('#bgForm')。followTo(1550);這是形式,它具有固定的位置,當你向下滾動時,形式隨你而去。但我想在準確的地方停下來 - 1550 px。我如何在代碼中包含這個需求? – Steve

1

我看不到爲什麼你會使用Javascript時,一個簡單的CSS媒體查詢就足夠了。除非你有更多的問題沒有說明?

@media only screen and (max-width: 992px) { 
    // Rules placed here will only apply when the 
    // browser window is smaller than 992px 
} 
相關問題