gpt4 book ai didi

javascript - 如何使用纯 javascript 检测文本区域大小变化?

转载 作者:太空狗 更新时间:2023-10-29 16:07:32 24 4
gpt4 key购买 nike

我想在 textarea 的大小发生变化时通知,那时候发生了什么事件,我该如何检测?

最佳答案

这是一个使用纯(没有 jQuery 等依赖项)Javascript 的小示例。

它使用 mouseup 和 keyup 处理程序以及一个可选的间隔来检测更改。

var detectResize = (function() {

function detectResize(id, intervall, callback) {
this.id = id;
this.el = document.getElementById(this.id);
this.callback = callback || function(){};

if (this.el) {
var self = this;
this.width = this.el.clientWidth;
this.height = this.el.clientHeight;

this.el.addEventListener('mouseup', function() {
self.detectResize();
});

this.el.addEventListener('keyup', function() {
self.detectResize();
});

if(intervall) setInterval(function() {
self.detectResize();
}, intervall);

}
return null;
}

detectResize.prototype.detectResize = function() {
if (this.width != this.el.clientWidth || this.height != this.el.clientHeight) {
this.callback(this);
this.width = this.el.clientWidth;
this.height = this.el.clientHeight;
}
};

return detectResize;

})();

用法:new detectResize(element-id, interval in ms or 0, callback function)

例子:

<textarea id="mytextarea"></textarea>
<script type="text/javascript">
var mytextarea = new detectResize('mytextarea', 500, function() {
alert('changed');
});
</script>

jsfiddle.net/pyaNS 上查看实际效果.

关于javascript - 如何使用纯 javascript 检测文本区域大小变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16937721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com