[英]Saving and loading the caret position in a textarea via JavaScript
I'm looking for a method to save and load the caret position in a textarea in a web-application, so that when the user re-opens the web-application they are automatically taken back to the position they left it. 我正在寻找一种方法来保存和加载Web应用程序中textarea中的插入位置,这样当用户重新打开Web应用程序时,它们会自动返回到它们离开它的位置。
I've seen the jCaret plugin for jQuery, but as my web application does not use jQuery I need something that works in pure JavaScript. 我见过jQuery的jCaret插件,但由于我的web应用程序不使用jQuery,我需要一些适用于纯JavaScript的东西。
Also, what would be the best way of initiating the function to save the caret's position? 另外,启动功能以保存插入符号位置的最佳方法是什么? The first method that came to mind was re-saving it on every keypress, but this seems a little inefficient.
想到的第一种方法是在每个按键上重新保存它,但这似乎有点低效。 I've been thinking of having the application save the position via the onBeforeUnload event, but if you can think of a better way please share!
我一直在考虑让应用程序通过onBeforeUnload事件保存位置,但是如果你能想到更好的方法请分享!
With some minor modifications, you can use jCaret without jQuery. 通过一些小修改,您可以使用jCaret 而不使用jQuery。 I had a look at the jCaret source, and it uses jQuery for all of two things: to supply the element using jQuery selectors, and to test if the browser is IE.
我看了一下jCaret源代码,它使用jQuery来完成所有两件事:使用jQuery选择器提供元素,并测试浏览器是否为IE。 Get rid of these and you're on your way.
摆脱这些,你就在路上。
More detailed instructions: 更详细的说明:
var caret;
var caret;
to the top. $,
from (function($,len,createRange,duplicate){
(function($,len,createRange,duplicate){
删除$,
(function($,len,createRange,duplicate){
$.fn.
$.fn.
from $.fn.caret=function(options,opt2){
$.fn.caret=function(options,opt2){
var start,end,t=this[0],browser=$.browser.msie;
var start,end,t=this[0],browser=$.browser.msie;
to var start,end,t=this[0],browser=/(msie) ([\\w.]+)/.test(navigator.userAgent);
var start,end,t=this[0],browser=/(msie) ([\\w.]+)/.test(navigator.userAgent);
jQuery,
from })(jQuery,"length","createRange","duplicate");
jQuery,
来自})(jQuery,"length","createRange","duplicate");
To use it, you need to do: 要使用它,您需要:
caret.call([document.getElementById("myText")], options, opt2);
After further research, I've come to a simple solution that uses HTML5 localStorage. 经过进一步研究,我找到了一个使用HTML5 localStorage的简单解决方案。
Here's the script I made for saving the caret position: 这是我为保存插入位置而制作的脚本:
function caretPositionSave() {
window.localStorage.setItem("CaretPosition", document.querySelector("#editor").selectionStart);
};
And another one for loading it: 另一个用于加载它:
function caretPositionLoad() {
document.querySelector("#editor").focus();
if (localStorage.CaretPosition) {
document.querySelector("#editor").selectionStart = localStorage.CaretPosition;
};
};
These, combined with similar functions to set the screen's scroll position, seem to do the trick perfectly! 这些与设置屏幕滚动位置的类似功能相结合,似乎完美无缺!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.