4

大多数现代浏览器在 textarea 元素上都有调整大小的句柄。问题是他们不会自动记住您每次访问时离开他们的地方。

我想为我的应用启用此功能。为此,我计划使用 jQuery(将 textarea resize 绑定到函数)以及 html5 localStorage 对象,以便将 textarea 元素的高度和宽度写入 localStorage 项。

我需要将 localStorage 写入事件绑定到表示 textarea 已调整大小的等效 jQuery 事件。

将函数绑定到的相关 jQuery 方法是什么?

4

2 回答 2

2

您只能绑定到窗口的调整大小事件,而不是 textarea 的。你需要做的是创建一个轮询函数来监听大小,如果它发生变化,更新。

像这样的东西:

var checkSize = setInterval(function(){ 
    var $text = $('#myTextArea');
    if (localStorage && localStorage.myTextAreaWidth) {
        if ($text.width() != localStorage.myTextAreaWidth) {
            localStorage.myTextAreaWidth  = $text.width();
        }
        if ($text.height() != localStorage.myTextAreaHeight) {
            localStorage.myTextAreaHeight = $text.height();
        }
    } else {
        localStorage.myTextAreaWidth  = $text.width();
        localStorage.myTextAreaHeight = $text.height();
    }
}, 1000);

$(function(){
    var $text = $('#myTextArea');
    if (localStorage && localStorage.myTextAreaWidth) {
        $text.css({
            width  : localStorage.myTextAreaWidth  + 'px',
            height : localStorage.myTextAreaHeight + 'px'
        });
    } 
});

这是一个演示:http: //jsfiddle.net/TDKpr/

您可以通过在小提琴中调整大小、关闭选项卡、打开一个新选项卡、重新访问小提琴来查看它正在工作,并且 textarea 保持您上次选择的大小。

于 2013-02-28T05:21:22.097 回答
1

如果您喜欢使用 localStorage,这可能对您有所帮助:

html

<textarea class="rz" id="txt_id_1" cols="40" rows="5">resize test</textarea>

jQuery

$(document).ready(function(){
//on load set the default or history size
var track_ta='txt_id_1';

initSize();

function initSize(){
   var ta_size=localStorage.getItem(track_ta);
   //default size
   if(ta_size==null) ta_size={width:'200px', height:'50px'};
   else ta_size=JSON.parse(ta_size);
   $('#'+track_ta).css(ta_size);
}

//keep the latest in the local storage
$("textarea.rz").resizable({
    resize: function() {  
       var sizeHistory=JSON.stringify({width:this.style.width,height:this.style.height});
       localStorage.setItem(track_ta,sizeHistory);
    }
});
});

工作演示http://jsfiddle.net/PPZEK/,只需调整大小并重新加载页面。

您可以概括所有 textarea 的概念。正如我所见,textarea 的默认调整大小处理程序不提供任何调整大小事件,显然我们必须使用 jquery 调整大小。

于 2013-02-28T06:38:11.517 回答