简体   繁体   English

如何滚动以自动滚动到可编辑div加载的底部

[英]How to scroll to automatically scroll to the bottom of an editable div onload

How can I get an editable div to remember the position of the scroll bar? 如何获得可编辑的div来记住滚动条的位置? Im currently programming a Chrome extension and have a notepad style editable div which users can write notes in. I have the code listed below currently which autofocuses the div onload and displays the caret at the end of the text within the div. 我目前正在编程一个Chrome扩展程序,并具有一个记事本样式可编辑的div,用户可以在其中编写笔记。我下面列出了当前可自动调整div加载焦点并在div内文本末尾显示插入符号的代码。

I now just need my scroll bar to scroll level with the caret if its further down the div. 现在,我只需要滚动条就可以将插入符号的水平滚动到div下方。

    var div = document.getElementById("edit_notepad");

div.onfocus = function() {
    window.setTimeout(function() {
        var sel, range;
        if (window.getSelection && document.createRange) {
            range = document.createRange();
            range.selectNodeContents(div);
            range.collapse(false);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(div);
            range.collapse(false);
            range.select();
        }
    }, 1);
};

div.focus();

You may want to try the different approaches done in Scroll to bottom of Div on page load (jQuery) and choose which best suits your concern. 您可能需要尝试在页面加载(jQuery)上滚动到Div的底部并选择最适合您的关注的其他方法。

One suggested solution is to scroll down to the height of the div as suggested by @Mike Todd 一种建议的解决方案是按照@Mike Todd的建议向下滚动到div的高度。

Correct version: 正确版本:

$('#div1').scrollTop($('#div1')[0].scrollHeight);

This related SO post might also help. 相关的SO帖子也可能会有所帮助。

Why don't you try some simple localStorage ? 为什么不尝试一些简单的localStorage

var position = localStorage.position || 0;
div.scrollTop = position;
localStorage.setItem("position", div.scrollTop);

The code above should get and set the position of the div scroll amount, as far as I know. 据我所知,上面的代码应该获取并设置div滚动量的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM