javascript - 以编程方式调整文本区域的大小而不修改最小大小

标签 javascript jquery css html textarea

如你所见here , textarea 不会调整到 100px*100px 以下。显然,这是正常行为。

但是我怎样才能将文本区域初始化为自定义大小,然后让用户在不使用 jQuery ui 的情况下将其调整为他想要的大小(更大和更小)?

唯一的方法似乎是使用鼠标按下/移动/向上事件,对吧?

Here是一个相关问题(没有相关答案)。

最佳答案

在 Chrome 中,您无法将 textarea 的大小调整为小于其原始 heightwidth 的大小。

这实际上是在 W3C specifications 中指定的,这表明浏览器可以定义这样的特征:

The user agent may restrict the resizing range to something suitable, such as between the original formatted size of the element, and large enough to encompass all the element's contents.

也就是说,这也被提出为 bug in Chrome

但是,您可以使用 Javascript 覆盖它,只需为您的文本区域指定类 resizable 并将以下内容添加到您的页面:

Demo Fiddle

function resizableStart(e){
    this.originalW = this.clientWidth;
    this.originalH = this.clientHeight;
    this.onmousemove = resizableCheck;
    this.onmouseup = this.onmouseout = resizableEnd;
}
function resizableCheck(e){
    if(this.clientWidth !== this.originalW || this.clientHeight !== this.originalH) {
        this.originalX = e.clientX;
        this.originalY = e.clientY;
        this.onmousemove = resizableMove;
    }
}
function resizableMove(e){
    var newW = this.originalW + e.clientX - this.originalX,
        newH = this.originalH + e.clientY - this.originalY;
    if(newW < this.originalW){
        this.style.width = newW + 'px';
    }
    if(newH < this.originalH){
        this.style.height = newH + 'px';
    }
}
function resizableEnd(){
    this.onmousemove = this.onmouseout = this.onmouseup = null;
}
var els = document.getElementsByClassName('resizable');
for(var i=0, len=els.length; i<len; ++i){
    els[i].onmouseover = resizableStart;
}

关于javascript - 以编程方式调整文本区域的大小而不修改最小大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23015293/

相关文章:

javascript - 如何在单独的 'thread' 中或异步应用模板绑定(bind)?

javascript - 使用ajax从chartjs填充动态饼图

javascript - 在 Chrome 扩展中运行 JQuery

jquery - CSS3 变换scale() 确实对一些元素进行像素化

html - 边框长度小于 div 宽度?

javascript - 我可以缓存由 jQuery.getScript() 加载的内容吗

javascript - AWS Cognito 更新多个用户属性

javascript - 谷歌浏览器网络请求冲突?

html - CSS - 设置表格列高百分比更改行高

css - 将按钮放置在 div 的底部