简体   繁体   中英

Setting Scroll Position on PostBack

I am writing in asp.net c# code.

I want to control the page position on a post back. Neither MaintainScrollPositionOnPostback equal true or false, is what I want. True is too low and False is too high. Another problem is that the position should be different depending on which control is press. A third issue is that MaintainScrollPositionOnPostback=true works in IE but not in Firefox.

Want I want is similar to the href related tags eg <a href="#body2"> except in code.

Thanks for any suggestions.

Assuming you are able to use JQuery, try the following:

http://abeautifulsite.net/blog/2010/01/smoothly-scroll-to-an-element-without-a-jquery-plugin/

Just inject script and pass the ID of the control that fired your postback event.

If you cannot use jquery for some reason, here is a less elegant approach:

http://clifgriffin.com/2008/10/14/using-javascript-to-scroll-to-a-specific-elementobject/

Edit (Samples):

Here is an example of straight html using the jquery method, presuming you have a script file named jquery.js in the same folder as the html page.

<html>
<head>
    <script type='text/javascript' src='jquery.js'></script>
    <script type='text/javascript'>
    $(document).ready(function() {
        $('html,body').animate({ 
            scrollTop: $('#scrollHere').offset().top 
            }, 0//increase for smooth, visible scroll
        );
    });
    </script>
</head>
<body>

<div style='width:100px; height:1000px; background-color:red;'>
top filler
</div>

<a id='scrollHere' href='#'>Scrolls to this element</a>

<div style="width:100px; height:1000px; background-color:blue;">
bottom filler
</div>

</body>
</html>

Here is an example of a client-side method that you can pass the "ClientID" property of any visible page control and it will register the javascript to scroll to the element on page load (assumes jquery is registered on the page and only registers one call per request):

private void ScrollToControl(string controlId)
{
    //scroll to button
    string script =
        "$(document).ready(function() {" +
            "$('html,body').animate({ " +
                "scrollTop: $('#" + controlId + "').offset().top " +
            "}, 0);" +
        "});";

    if (!Page.ClientScript.IsStartupScriptRegistered("ScrollToElement"))
        Page.ClientScript.RegisterStartupScript(this.GetType(), "ScrollToElement", script, true);
}

Maintain page scroll position on button click by:

$("#Next").click(function() { $('html,body').animate(
{ scrollTop: $('.required').offset().top 
}, 0//increase for smooth, visible scroll ); });

如果您知道要在窗口中放置的特定像素值,则可以尝试使用Javascript中的window.scrollTo()函数。

window.scrollTo(0,0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM