2016-04-20 51 views
0

我正在對錶單的JavaScript驗證。我的問題是,在提交表單時,瀏覽器會自動跳轉到空單元格。這不是問題,我喜歡這種方式。我的問題是,我的頁面上顯示了一個固定的標題,並且此標題覆蓋了表單字段。有什麼辦法可以解決它嗎?謝謝!表單驗證autoscroll修改javascript

回答

1

我有同樣的問題,並固定它是這樣的:

事件監聽綁定:

$('input').on('invalid',function() { 
    scrollToInvalid(); 
    }); 

功能:

function scrollToInvalid() { 

    //Height of your nav bar with some offset 
    var navHeight = $('nav#main').height() + 20; 

    // Offset of the first input element minus your nav height 
    var firstInvalidPosTop = $('input:invalid').first().offset().top; 
    var newScrollPos  = firstInvalidPosTop - navHeight; 

    // return true if the invalid element is already within the window view. 
    // If you return false, the validation will stop. 
    if ( newScrollPos > (window.pageYOffset + navHeight) && 
     newScrollPos < (window.pageYOffset + window.innerHeight - navHeight)) { 
    return true; 
    } else { 

    // If the first invalid input is not within the current view, scroll to the new position. 
    $('html, body').scrollTop(newScrollPos); 
    } 
}; 
+0

作品完美,太感謝你了!祝你有美好的一天! – donfrigo

+0

沒問題,你也是(: – LeaveAirykson