简体   繁体   中英

Javascript Scrolling to a PHP variable Scroll point passed through a link

I'm trying to create a page that has anchor tags that link to another page containing a variable for a javascript function on the other page to scroll the window to. As is, I am pointing the link to the next page like so:

<a href="products/cartridges/?scrollpoint=600">721p</a>

With a PHP script on the receiving page GETing the linked variable and echoing it into javascript in the head of the document.

<?php>
$scrollpoint = $_GET["scrollpoint"];
echo "<script type='text/javascript'>";
echo "var scrollpoint = " . $scrollpoint . ";";
echo "function scrollWindow {"; 
echo "window.scrollTo(0,$scrollpoint);";
echo "}"; 
echo "window.onload = scrollWindow;";
echo "</script>";
?>

The PHP should be executed before the javascript runs, so What am I doing wrong here?

I would prefer not to use jquery, or scrolling to a div id, the page is relatively short, and the spans that are being scrolled to aren't assigned IDs.

Two things:

  1. Your function signature for scrollWindow needs to have () in order to be valid js: function scrollWindow () {...}
  2. This needs to be inserted near the bottom of the page in order for it to fire at the time you expect it to. Even then I'm not sure it's 100% that it'll fire and scroll to the right spot every time, but if the page is simple it'll probably work.

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