如何滚动发布表单

时间:2016-10-20 18:23:05

标签: javascript php jquery post cookies

我有一个表单,我想做一件事:当我点击de按钮并发布表单时,我想滚动到一个特定点。我尝试过使用cookies,我的代码是这样的: `

<!-- I have a library called cookie and the cookie works well, but when I send, the page go up and I want to stay in the scroll position -->
<form method="post" action="">
    <input type="submit" value="send" name="btn" /></div>
</form>
<script>
    function send() {
        cookie.asignar("altura", $(window).scrollTop(), "../js/", 10);
        $(window).scrollTop(0, cookie.agafar("altura"));
        cookie.suprimir("altura");
    }
</script>
<?php
    if (isset($_POST['btn'])) {
        echo '<script>send();</script>';
    }
?>

我使用jquery和php。

4 个答案:

答案 0 :(得分:0)

Just use an anchor on page

  <a name="form"></a> 

<form method="post" action="">
  <input type="submit" value="send" onclick="send();"name="btn" /></div>
</form>
<script>
  function send() {

    window.location.hash = '#form';
  }
</script>

答案 1 :(得分:0)

Well, trying another solution using localStorage instead of cookies:

<form method="post" action="">
    <input type="submit" value="send" name="btn" /></div>
</form>
<script>
    $(document).ready(function(){
      // Scroll to screen height if previously saved
      var previousHeight = localStorage.getItem("pageHeight");
      if(previousHeight){
        $('html, body').animate({
          scrollTop: localStorage.getItem("pageHeight")
        }, 1000);
        localStorage.setItem("pageHeight", null);
      }

      // Saves scroll height on submit
      $("form").on("submit", function(){
        localStorage.setItem("pageHeight", $(window).scrollTop());
      });
    });
</script>

答案 2 :(得分:0)

It's easy to jump to any position in your page, all you need is a local anchor, example (copy paste next code in a PHP file and run it in your browser) :

<form method="post">
  Enter number <input type="text" name="num" />
  <input type="submit" value="Submit"/>
</form>

<?php
for ( $i = 1; $i <= 200; $i++ ) // DISPLAY 200 NUMBERS.
  echo "<a name='$i'>$i</a>\n" . //◄■■■ LOCAL ANCHORS.
       "<br/>";
?>

<?php
if ( isset( $_POST["num"] ) )
   echo "<script type='text/javascript'>\n" .
        "window.location.hash = '#{$_POST["num"]}';" . //◄■■■ JUMP TO LOCAL ANCHOR.
        "</script>\n";
?>

Notice how the numbers are enclosed between <a name and </a>. These are the local anchors. Watch your address bar everytime you submit the form.

答案 3 :(得分:0)

I think the issue is that you need to target the "body,html" and not window.

$("body,html").scrollTop(0);

you can also just scroll into element:

$el = $(element).offset().top;
$("body,html").scrollTop($el);

quick example of scrollTop animated https://jsfiddle.net/keinchy/gLwz9n81/

hope this is helpful.

-cheers.