簡體   English   中英

如何在javascript中滾動到模態窗口的頂部

[英]How to scroll to the top of a modal window in javascript

我的要求是我需要將模態窗口顯示為要由用戶填充的表單。 但是該模態的高度不應超過窗口大小。

因此,如果表單中的條目太多,則模態變為可滾動。 問題是,在驗證表單中的條目時,錯誤消息顯示在第一個條目上方的模式頂部。 如果用戶位於最后一個屬性,那么除非模態在錯誤事件上滾動到頂部,否則他不會知道發生了一些驗證錯誤。

我試過了 :

$(window).scrollTop();
// and
$('#modalId').scrollTop();

這是模態代碼:

<div class="modal hide" id="groupModal" tabindex="-1" role="dialog" aria-hidden="true" >
    <div class="modal-header">
    </div>
    <div class="modal-body" style="max-height: 300px;">
        <div class="grpForm">
            <div class="alert alert-error hide">

                <span class="errMsg"></span>
            </div>
            <div class="alert alert-success hide">

                <span class="successMsg"></span>
            </div>
            <form class = "formFieldHolder" id="groupInfoForm"></form>
          </div>
    </div>
    <div class="modal-footer">
        <button class="btn cancelFormBtn" data-dismiss="modal" aria-hidden="true" msgkey="common.cancel.label"></button>
        <button class="btn btn-primary submitGroupFormBtn" type="submit" msgkey="common.submit.label"></button>     
    </div>
</div>

$('#modalId').scrollTop(0);

scrollTop()只返回值; scrollTop(0)將值設置為0(一直到頂部)

要將頁面滾動到模態,請選擇html, body並滾動到模態的偏移頂部

$("html, body").scrollTop($("#modalId").offset().top);

如果要將模態div滾動到頂部使用

$("#modalId").scrollTop(0);

關於jsFiddle的示例

如果需要,您可以將兩者結合使用以將模式滾動到用戶可見區域。

參考

這是一個不使用JQuery的解決方案,首先你通過id得到你的模態然后,函數scrollIntoView將移動到你選擇的元素的頂部,在這種情況下你的模態。

let element = document.getElementById('groupModal');    
element.scrollIntoView(true);
 <script type="text/javascript">
            $(document).ready(function(){ 
            $('.scroll_top').hide();
            $(window).scroll(function(){
                if ($(this).scrollTop() > 100) {
                    $('.scroll_top').fadeIn();
                } else {
                    $('.scroll_top').fadeOut();
                }
            }); 

            $('.scroll_top').click(function(){
                $("html, body").animate({ scrollTop: 0 }, 500);
                return false;
            });

        });
</script>

為了避免粗暴移動到頂部,我寧願使用(動畫運動):

$('#modalId').animate({
        scrollTop : 0
    }, 'slow');

您必須在頁面中包含“jquery-1.7.1.min.js”文件。 http://code.jquery.com/jquery-1.7.1.min.js

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM