2010-08-23 71 views
3

當選項卡低於視口底部的表單字段(或鍵入與底部重疊的文本區域)時,瀏覽器通常會自動向上滾動,以便您可以看到字段。有沒有辦法設置瀏覽器移動的位置?瀏覽器自動滾動通過表單元素跳轉

這是一個問題,因爲我在頁面底部有一個固定的位置欄,所以它覆蓋了瀏覽器滾動到的位置,並希望它進一步向上滾動。

乾杯

回答

1

當然,你可以一個焦點事件處理程序添加到您的輸入,並檢查他們的位置的onfocus。如果它太接近底部,只需將窗口滾動一下,直到可以接受爲止。

下面是你如何能做到這一點jQuery中:

// Constant amount of padding an element should be from the bottom of the window 
var padding = 50; 

// Add focus event to all your different form elements 
$("input, textarea, select").focus(function(){ 

    // Check their position relative to the window's scroll 
    var elementBottom = $(this).offset().top + $(this).height(); 
    var windowScroll = $(window).scrollTop(); 
    var windowBottom = windowScroll + $(window).height(); 

    if(elementBottom + padding > windowBottom){ 
     $(window).scrollTop(windowScroll + padding); 
    } 

}); 

你可以看到它in action here

編輯:打字在textarea的

您可以捕捉並檢查使用keydown event處理程序編寫過程中textarea的位置:

$('textarea').keydown(function(){ 
    // same logic as above to check textarea position relative to window 
}); 
+0

帕特您好,感謝您的答覆,我也結束了這樣做。但也有這樣一個事實,即當在與視口底部重疊的文本區域中輸入時,窗口會滾動到光標,以使其不會消失。這也有可能改變嗎? – Joel 2010-08-24 11:25:14

+0

不是問題,並確定它是可能的 - 請參閱我的編輯以瞭解如何執行此操作。 – Pat 2010-08-24 11:51:24

相關問題