[英]How to detect textarea size change with pure javascript?
我想在textarea的大小发生变化时发出通知,当时发生了什么事,我该如何检测呢?
这是一个使用纯(没有jQuery等依赖)Javascript的小例子。
它使用mouseup和keyup处理程序以及可选的intervall来检测更改。
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, intervall 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(假设你没有使用jQuery或正在使用另一个库):
<textarea id="t"></textarea>
<script>
var t = document.getElementById('t'),
tHeight = t.clientHeight,
tWidth = t.clientWidth;
console.log(t);
t.onmouseup = function (e) {
if (tHeight !== t.clientHeight || tWidth !== t.clientWidth ) {
console.log('size change');
tHeight = t.clientHeight;
tWidth = t.clientWidth;
}
};
</script>
我已经包含了元素的控制台日志,因此您可以在检查器中查看可以使用的事件。
当他尝试更改textarea的大小时,您可以拦截用户的鼠标事件。
1: Element .addEventListener("mousedown", event => {})
:开始拦截。
2: window .addEventListener("mousemove", event => {})
:这里比较了每个移动事件的先前和当前大小。
window .addEventListener("mouseup", event => {})
:停止拦截。 试试这个演示。
jQuery(document).ready(function(){
var $textareas = jQuery('textarea');
// set init (default) state
$textareas.data('x', $textareas.outerWidth());
$textareas.data('y', $textareas.outerHeight());
$textareas.mouseup(function(){
var $this = jQuery(this);
if ( $this.outerWidth() != $this.data('x')
|| $this.outerHeight() != $this.data('y') )
{
alert( $this.outerWidth() + ' - ' + $this.data('x') + '\n'
+ $this.outerHeight() + ' - ' + $this.data('y')
);
}
// set new height/width
$this.data('x', $this.outerWidth());
$this.data('y', $this.outerHeight());
});
});
无法在纯JavaScript中使用我们必须使用jQuery
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.