输入时自动滚动

时间:2019-02-07 21:28:40

标签: javascript jquery

大家好!

我想知道如何启用自动滚动? 当前,当您在我的网站上键入许多命令时,必须使用鼠标手动向下滚动才能看到响应。您也不能使用箭头键,因为它们当前正用于遍历命令历史记录。我正在通过自动向下滚动jquery进行研究,但是它们都不起作用!

网站背后的想法是它应该像终端一样工作,并且当您输入输入和接收输出时,窗口应该像普通终端一样自动向下滚动。

此刻,我尝试将注意力集中在div类上,但这并不成功。我也尝试过使用

我也尝试使用这段代码:

$('terminal').animate({
    scrollTop: $('terminal').get(0).scrollHeight
}, 1500);

但是我认为它没有用,因为在开始处没有滚动条,并且在开始处只滚动一次,并且在出现提示时不会连续滚动。

这是我的website,其代码可以在github仓库here

中找到

谢谢您的时间!

我的index.html文件:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png">
  <title>BitVivAZ Terminal</title>
  <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
  <meta name="description" content="The HTML5 Herald">
  <meta name="author" content="SitePoint">
  <link type="text/css" rel="stylesheet" href="css/index.css" />
  <script src="scripts/index.js"></script>
  <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin">

</head>

<body>

    <div class="container">
        <div class="window">
                <div class="handle">
                    <div class="buttons">
                        <button class="close">
                        </button>
                        <button class="minimize">
                        </button>
                        <button class="maximize">
                        </button>
                    </div>
                        <span class="title"></span>
                </div>
                <div class="terminal"></div>
        </div>
</div>

</body>
</html>

我的index.js文件:

var username = prompt("Please enter your name:", "name");
if (username === null ){
    username = "user";
}


$(document).ready(function() {

    // COMMANDS
    function ls(){
        for (var i = 0; i < files.length; i++) {
            terminal.append(files[i].name + "\t\t");
        }

        terminal.append(lineBreak);
    }

    function nano(args) {
        var str = args;
        var fileFound = false;
        for (var i = 0; i < files.length; i++) {
            if (str.toString() === files[i].name){
                fileFound = true;
                terminal.append(files[i].content + lineBreak);
            }
        } 
        if (!fileFound) {
            terminal.append("cannot access \'" + str + "\' : No such file or directory" + lineBreak);
        }
    }

    function clear() {
        terminal.text("");
    }

    function echo(args) {
        var str = args.join(" ");
        terminal.append(str + "\n");
}

    function date(){
        // Get the date for our fake last-login
        var date = new Date().toString(); date = date.substr(0, date.indexOf("GMT") - 1);
        terminal.append("Today is " + date + lineBreak);
    }

    function help(args){
        var str = args;
        if (str.toString() === "") {
            terminal.append("Supported commands are:" + lineBreak); 
            terminal.append("\t -  ls:  list directory contents" + lineBreak);
            terminal.append("\t -  nano:  open and print files. e.g. nano [FILENAME]" + lineBreak);
            terminal.append("\t -  clear:  clear the terminal screen" + lineBreak);
            terminal.append("Bonus Commands are:" + lineBreak);
            terminal.append("\t -  echo:  prints input as text in the terminal. e.g. echo [INPUT]" + lineBreak);
            terminal.append("\t -  date:  return today's date and current time." + lineBreak);

        } else {
            for (var i = 0; i < commands.length; i++){
                if (str.toString() === commands[i].name){
                    terminal.append(commands[i].help + lineBreak);
                }
            }
        }

    }


    // END COMMANDS

    var title = $(".title");
    var terminal = $(".terminal");
    var prompt = username + "@vivaz";
    var path = ": ~";
    var lineBreak = "<br>";

    var commandHistory = [];
    var historyIndex = 0;

    var command = "";
    var commands = [{
                    "name": "clear",
                    "function": clear
            }, {
                    "name": "help",
                    "function": help
            }, {
                    "name": "echo",
                    "function": echo
            }, {
                    "name": "date",
                    "function": date
            }, {
                    "name": "ls",
                    "function": ls
            }, {
                    "name": "nano",
                    "function": nano
            }];

    var files = [{
                    "name": "README.md",
                    "content": lineBreak + "Name: Martin" + lineBreak + "Surname: Buxmann" + lineBreak + "Date of Birth: 23/02/1996" + lineBreak + "Place of Birth: Pretoria, South Africa" + lineBreak + lineBreak + "Created to learn and to create anything from gfx to programming" + lineBreak
            }, {
                    "name": "github.txt",
                    "content": "<a href=\"https://github.com/bitVivAZ\">GitHub Website</a>"
            }, {
                    "name": "projects.txt",
                    "content": 
                                lineBreak + 
                                "<div class=\"project_title\">Severe Gaming Website</div>" + 
                                lineBreak + 
                                "I have huge passion for eSports especially for DOTA 2 and thought it would be a great way " + 
                                "to learn Django and Python by creating a website for Severe Gaming, a multi gaming organization that I manage!" + lineBreak + 
                                lineBreak + 
                                "Made using: Django, Python, CSS, HTML, jQuery" + 
                                lineBreak + 
                                "Github repo : <a href=\"https://github.com/bitVivAZ/SeveregamingZA\" target=\"_blank\">https://github.com/bitVivAZ/SeveregamingZA</a>" + 
                                lineBreak + 
                                "Domain : <a href=\"https://www.severegaming.co.za\" target=\"_blank\">https://www.severegaming.co.za</a>"  + 
                                lineBreak
            }];


function processCommand() {
    var isValid = false;

    // Create args list by splitting the command
    // by space characters and then shift off the
    // actual command.

    var args = command.split(" ");
    var cmd = args[0];
    //console.log(cmd);
    args.shift();

    // Iterate through the available commands to find a match.
    // Then call that command and pass in any arguments.
    for (var i = 0; i < commands.length; i++) {
            if (cmd === commands[i].name) {
                    commands[i].function(args);
                    isValid = true;
                    break;
            }
    }

    // No match was found...
    if (!isValid) {
            terminal.append(command + ": command not found" + lineBreak);
    }

    // Add to command history and clean up.
    commandHistory.push(command);
    historyIndex = commandHistory.length;
    command = "";
}

function displayPrompt() {
    terminal.append("<span class=\"prompt\">" + prompt + "</span>");
    terminal.append("<span class=\"path\">" + path + "</span> ");}

// Delete n number of characters from the end of our output
function erase(n) {
    command = command.slice(0, -n);
    terminal.html(terminal.html().slice(0, -n));
}

function clearCommand() {
    if (command.length > 0) {
            erase(command.length);
    }
}

function appendCommand(str) {
    terminal.append(str);
    command += str;
}

/*
//  Keypress doesn't catch special keys,
//  so we catch the backspace here and
//  prevent it from navigating to the previous
//  page. We also handle arrow keys for command history.
*/

$(document).keydown(function(e) {
    e = e || window.event;
    var keyCode = typeof e.which === "number" ? e.which : e.keyCode;

    // BACKSPACE
    if (keyCode === 8 && e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") {
            e.preventDefault();
            if (command !== "") {
                    erase(1);
            }
    }

    // UP or DOWN
    if (keyCode === 38 || keyCode === 40) {
            // Move up or down the history
            if (keyCode === 38) {
                    // UP
                    historyIndex--;
                    if (historyIndex < 0) {
                            historyIndex++;
                    }
            } else if (keyCode === 40) {
                    // DOWN
                    historyIndex++;
                    if (historyIndex > commandHistory.length - 1) {
                            historyIndex--;
                    }
            }

            // Get command
            var cmd = commandHistory[historyIndex];
            if (cmd !== undefined) {
                    clearCommand();
                    appendCommand(cmd);
            }
    }
});

$(document).keypress(function(e) {
    // Make sure we get the right event
    e = e || window.event;
    var keyCode = typeof e.which === "number" ? e.which : e.keyCode;

    // Which key was pressed?
    switch (keyCode) {
            // ENTER
            case 13:
                    {
                            terminal.append("\n");

                            processCommand();
                            displayPrompt();
                            break;
                    }
            default:
                    {
                            appendCommand(String.fromCharCode(keyCode));
                    }
    }
});

$(terminal).trigger("focus");


// Set the window title
title.text(username + "@VivAZ:~");

// Display Welcome Message
terminal.append("Welcome " + username + ", to the bitVivAZ Terminal!" + lineBreak);
terminal.append("Some supported commands are:" + lineBreak);
terminal.append("\t -  ls:  list directory contents" + lineBreak);
terminal.append("\t -  nano:  open and print files. e.g. nano [FILENAME]" + lineBreak);
terminal.append("\t -  clear:  clear the terminal screen" + lineBreak);
terminal.append("\t -  help: lists all supported commands." + lineBreak);
displayPrompt();


});

$('terminal').animate({
    scrollTop: $('terminal').get(0).scrollHeight
}, 1500);

2 个答案:

答案 0 :(得分:2)

只需定义滚动功能即可测量div高度并滚动到底部,即:

function scrollToBottom() {
    $('.terminal').scrollTop($('.terminal')[0].scrollHeight);
}

并在displayPrompt()中执行它。

答案 1 :(得分:0)

按Enter键时,应将.terminal滚动到底部:

 let terminal = document.querySelector(".terminal");
 terminal.scrollTo(0,terminal.scrollHeight); //scrolls the height of the terminal