【问题标题】:.resize() function for textareatextarea 的 .resize() 函数
【发布时间】:2018-11-12 17:33:15
【问题描述】:

当用户更改其尺寸时,我想保存textarea 的高度和宽度。

我试过用:

$('textarea').resize(function() {

    var height = $('textarea').css('height');

    var width = $('textarea').css('width');

    $.post('vocabresize.php?height=' + height + '&&width=' + width, function() {});

});

但是$.post()函数没有被调用,所以我改成:

$('textarea').resize(function() {

    $('body').html('Yay it worked');

});

当我更改 textarea 的大小时,没有出现“Yay it works”。

【问题讨论】:

  • 对不起,我抄错了
  • 所以一种代码味道是您使用 $.post() 没有发布数据。您正在使用 url 查询字符串发送数据。
  • 你还有&&width=,这将是一个无效的url字符串

标签: javascript jquery events jquery-events


【解决方案1】:

textarea 在调整大小时不会触发resize 事件;那是为了调整窗口大小。相反,您可以将 textarea 的大小存储在函数之外,然后在释放鼠标时检查更改。像这样的东西会起作用:

let myTextArea = $('#myTextArea');
let oldHeight = myTextArea.height();
let oldWidth = myTextArea.width();

myTextArea.mouseup(function() {
    let newHeight = $(this).height();
    let newWidth = $(this).width();
    if(newHeight !== oldHeight || newWidth !== oldWidth) {
        console.log("Text area was resized!");
        oldHeight = newHeight;
        oldWidth = newWidth;
    }
})

请注意,这不会检测到 textarea 大小何时因其他原因发生变化;例如当窗口调整大小时。此外,要使其适用于页面上的每个文本区域,您需要遍历它们并将它们的尺寸存储在一个对象中,以便您可以检索它们。

【讨论】:

    【解决方案2】:

    .resize 不适用于 textarea 元素。我刚刚自己测试过。你可以这样做;)

    var textareaWidth;
    var textareaHeight;
    $('textarea').mouseup(function(evt) {
        if(this.clientWidth != textareaWidth || this.clientHeight != textareaHeight) {
            console.log(`new size= ${this.clientWidth} x ${this.clientHeight}`);
            textareaWidth = this.clientWidth;
            textareaHeight = this.clientHeight;
        }
    });
    

    【讨论】:

    • @Taplar 我的意思是 .resize() 不适用于 textarea 元素。
    • 我用两个辅助变量修复了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    相关资源
    最近更新 更多