2011-10-10 3 views
0

브라우저 세로 스크롤 막대의 위치를 ​​가져 와서 ASP 페이지의 세션 변수에 저장하는 간단하고 효율적인 방법을 찾고 있습니다.브라우저 스크롤 위치 유지

내가하려고하는 것은 사용자가 페이지를 변경할 때 내가 세션 변수에 저장된 스크롤 위치를 가졌기 때문에 사용자가 페이지로 돌아 오면 페이지가 마지막 위치로 스크롤됩니다.

이 방법이 있습니까? 나는 다시 게시의 스크롤 위치를 지속하지만 아직 아무것도 나는 사람이 감사 할 올바른 방향 아이디 날 지점 수 있다면 :(

을 할 노력하고있어 정확히 무엇을하고하지의 예를 본 적이

편집 :.

좋아, 아래 예제를 기반으로 사용자가 내 gridview에서 행을 클릭하면 다음 페이지로 이동하지만 이벤트 처리기가 결코 실행되지 않는다는 것을 알게되었습니다. 이렇게하면 스크롤 위치가 저장 됨, 양식을 제출하지 않는 것 같음)

내 이벤트 처리기 모양 : 나는 값을 잡기 위해의 valueChanged 이벤트를 사용하고 세션

다음 내 스크립트에 넣어하는 것이 가장 생각 했어요

Protected Sub save(ByVal sender As Object, ByVal e As EventArgs) Handles ScrollPosition.ValueChanged 
     Session.Add("ScrollPosition", ScrollPosition.Value) 
    End Sub 

.... 나는 그것을 기반으로 할 노력하고있어 Jquery에 대한 나의 매우 제한된 지식!

<script type="text/javascript"> 
    $(function() { 

     //Retrieve and use the existing scroll position from the hidden field 
     var scrollPosition = $('#<%= ScrollPosition.ClientID %>').val(); 
     $(window).scrollTop(scrollPosition); 
     /* 
     //Handle the main forms submit event and store the scroll position 
     $('#<%= form1.ClientID %>').submit(function() { 
     var currentScrollPosition = $(window).scrollTop(); 
     $('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition); 
     }); 
     */ 
    }); 

    $(document).ready(function() { 
     $("#gvTickets").click(function() { 
     var currentScrollPosition = $(window).scrollTop(); 
     $('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition); 
     }) 
    }); 
</script> 

스크립트 뒤에 아이디어는 gvTickets의 행을 클릭하면 스크롤 위치가 나는 오류를받지 못했습니다 내 값 변경 이벤트 핸들러

를 실행해야하는 저장된다는 것입니다하지만 나도 오전 없습니다

그런

If (Session("ScrollPosition") = Nothing) Then 
    ScrollPosition.Value = 0 
    Session("ScrollPosition") = 0 
Else 
    ScrollPosition.Value = Session("ScrollPosition") 
End If 
하지 IsPostBack을 경우 : 내가 가진 원하는 동작 :(페이지로드에서 또한

을 받고

답변

2

HiddenField 컨트롤에서 양식 제출시 스크롤 위치를 저장해보십시오.

HiddenField 컨트롤은 코드 숨김에서 사용할 수 있으므로 필요에 따라 값을 저장할 수 있습니다.

그런 다음 HiddenField 컨트롤의 값을 사용하여 페이지가로드 될 때 스크롤 위치를 설정할 수 있습니다.

아래의 예를 참조하십시오 (JQuery와 사용) :

마크 업

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
    <!-- Set the path to JQuery here --> 
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(function() { 
      //Add some line breaks 
      for (i = 0; i < 1000; i++) { 
       $('body').prepend('<br/>'); 
      } 

      //Retrieve and use the existing scroll position from the hidden field 
      var scrollPosition = $('#<%= ScrollPosition.ClientID %>').val(); 
      $(window).scrollTop(scrollPosition); 

      //Handle the main forms submit event and store the scroll position 
      $('#<%= form1.ClientID %>').submit(function() { 
       var currentScrollPosition = $(window).scrollTop(); 
       $('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition); 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <div> 
      <div style="position:fixed;top:0px;left:0px;"> 
       <asp:HiddenField ID="ScrollPosition" runat="server" Value="0" /> 
       <asp:Button ID="Button1" runat="server" Text="Post Back" OnClick="Button1_Click" /> 
       <asp:Label ID="CurrentScrollPosition" runat="server"></asp:Label>   
      </div> 
     </div> 
    </form> 
</body> 
</html> 

코드 (주석 기준)

protected void Button1_Click(object sender, EventArgs e) 
{ 
    CurrentScrollPosition.Text = string.Format("Scroll position: {0}", ScrollPosition.Value); 
} 

편집

0 뒤에

스크롤 위치가 변경 될 때마다 숨겨진 필드를 업데이트, 윈도우 스크롤 이벤트를 처리하십시오 :

<script type="text/javascript"> 
    $(function() { 

     $(window).scroll(function() { 
      var currentScrollPosition = $(window).scrollTop(); 
      $('#<%= ScrollPosition.ClientID %>').val(currentScrollPosition); 
     }); 

    }); 
</script> 

편집 나를 위해

, 다음 코드는 부하의 스크롤 위치 숨겨진 필드를 0으로 설정합니다. 그런 다음 후속 게시물 백스에서 "ScrollPosition"세션 변수의 숨겨진 필드에 값을 저장합니다.

그런 다음 스크롤 위치를 화면에 인쇄 할 수 있습니다. 아래 참조 :

내 예제에서 컨트롤을 실행하는 컨트롤은 Button이지만 어떤 컨트롤도 포스트 백을 시작할 수 있으며 여전히 같은 방식으로 작동합니다.

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     //Default to 0 
     ScrollPosition.Value = "0"; 

     //If ScrollPosition session variable is null, store the default 
     //Else set the scroll position to the value stored in session. 
     if (Session["ScrollPosition"] == null) 
     { 
      Session.Add("ScrollPosition", ScrollPosition.Value); 
     } 
     else 
     { 
      ScrollPosition.Value = Session["ScrollPosition"].ToString(); 
     } 
    } 
    else 
    { 
     //On subsequent postbacks store the new scroll position 
     Session.Add("ScrollPosition", ScrollPosition.Value); 
    } 

    OutputScrollPosition(); 
} 

private void OutputScrollPosition() 
{ 
    CurrentScrollPosition.Text = string.Format("Scroll position: {0}", Session["ScrollPosition"]); 
} 

희망이 있습니다.

+0

답장을 보내 주셔서 감사합니다. 어딘가에서 시작해 주셔서 감사합니다. 아직 답변이 없으므로 원본 게시물을 업데이트했습니다. – Purplegoldfish

+0

건배,이 접근 방식은 내가하고 싶은 일을 더 잘 보이지만 여전히 ScrollPosition.ValueChanged 이벤트 핸들러는 결코 호출되지 않습니다. 나는 왜 오류가 발생하는지 정말 모르겠다. ( – Purplegoldfish

+1

이유는 숨겨진 필드가 (js) 코드에서 업데이트되고 변경된 서버 측 이벤트를 시작하는 데 필요한 키 이벤트를 생성하지 않기 때문일 수있다. 그러나 숨겨진 필드에 대한 업데이트 빈도로 인해 스크롤 위치를 저장하는 가장 좋은 방법인지는 확실하지 않습니다. 페이지로드 이벤트에서 페이지가 다시 게시 될 때마다 스크롤 위치를 저장하지 않는 이유는 무엇입니까? – jdavies

관련 문제