How to automatically scrolling to the bottom of a

2019-08-06 06:34发布

问题:

I have a button that opens a TXT file in a new window. Is there a way to automatically go to the very bottom of that page using javascript or php? Or to any particular location (like searching for a string)? Because it is a TXT file, there are no anchors.

Here's my button's onclick:

onclick="window.open('comments.txt','_comments').focus();" 

I have looked into adding this to the onclick (but it did not work):

w.scrollTo(0,150);

回答1:

It's actually very easy to do:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>This is a test</title>
</head>
<body>

    <button id="open">Open text file</button>

    <script>
        document.getElementById('open').onclick = function(){
            window.open('comments.txt','_comments').onload = function(){
                this.scrollTo(0, 99999); // Use the biggest value you can
            };
        };
    </script>

</body>
</html>

Make sure you do this from a server (not locally), as browsers check that the files are on the same domain (for security reasons). If you want to work directly on your machine, install a local server and use http://localhost/.

Note: Here, I scroll to 99999px, because without an actual HTML document, we're not able to find out the document height. If that's not enough, use a higher value.