【问题标题】:auto scroll to dynamically generated control in ASP.NET自动滚动到 ASP.NET 中动态生成的控件
【发布时间】:2019-08-28 21:25:25
【问题描述】:

所以我有一个按钮,点击时会生成一个控件。它嵌套在 div 内的更新面板中,当它在 y 方向上溢出时将创建一个滚动条。目前,当我单击按钮并且它已经溢出时,将创建控件,尽管它不会滚动到它。所以好像什么都没发生。我希望滚动条向下滚动到创建控件的位置,这样对用户更友好。

我已经尝试过 Page.SetFocus(control) 和 control.Focus(),但两者都不起作用。我查看了其他帖子,但它们并没有完全解决问题,因为我生成的控件位于 updatePanel 中。

<!-- add button and dynamic control area -->
            <asp:Button ID="addStreamButton" runat="server" Text="+" OnClick="AddStreamButton_Click" Width="30px" Height="30px" Tooltip="add new stream"/>
            <div class="col-sm-6">
                <asp:UpdatePanel runat="server" ID="updatePanelPlaceholder" ChildrenAsTriggers="false" UpdateMode="Conditional"
                    style="width:650px; height:550px; overflow-y:auto; overflow-x:hidden">
                    <ContentTemplate>
                        <div class="row">
                            <asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
                        </div>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="addStreamButton" EventName="Click" />
                    </Triggers>
                </asp:UpdatePanel>

                <script type="text/html">
                    function scrollToControl(controlName) {
                        document.getElementById(controlName).scrollIntoView();
                    }
                </script>
            </div>
protected void AddStreamButton_Click(object sender, EventArgs e)
        {
            var userControl = (DataStreamSelector)Page.LoadControl("~/DataStreamSelector.ascx");
            userControl.ID = "DynamicControl" + ControlCount;
            ControlCount++;
            ph1.Controls.Add(userControl);

            //Page.Focus(userControl);
            Page.SetFocus(userControl);
        }

【问题讨论】:

    标签: javascript c# asp.net webforms


    【解决方案1】:

    您需要在客户端调用它。添加这个 AddStreamButton_Click 而不是焦点代码:

    ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>scrollToControl('" + userControl.ID.ToString() + "');</script>", false);
    

    这将调用您已经定义的 scrollToControl 方法。

    【讨论】:

    • 您好 DoubleJ,感谢您的回复。不幸的是,这对我不起作用——是因为我在更新面板中有一个占位符,该控件被添加到其中吗?目前,当我添加控件并且它不在视图中时,它只会将它添加到滚动窗口的底部,但仍然不会平移到它。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2010-10-19
    • 1970-01-01
    相关资源
    最近更新 更多