我想在 textarea 的大小发生变化时通知,当时发生了什么事件,我该如何检测它?
4 回答
Here is a small example using pure (without jQuery etc. dependencies) Javascript.
It's using mouseup and keyup handlers and an optional intervall to detect changes.
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;
})();
Usage: new detectResize(element-id, intervall in ms or 0, callback function)
Example:
<textarea id="mytextarea"></textarea>
<script type="text/javascript">
var mytextarea = new detectResize('mytextarea', 500, function() {
alert('changed');
});
</script>
See it in action on 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>
我已经包含了元素的控制台日志,因此您可以查看可以在检查器中访问哪些事件。
当用户尝试更改文本区域的大小时,您可以拦截用户的鼠标事件。
1: Element.addEventListener("mousedown", event => {})
: 开始拦截。
2: window.addEventListener("mousemove", event => {})
: 这里会比较每个移动事件的先前大小和当前大小。
window.addEventListener("mouseup", event => {})
: 停止拦截。
试试这个演示。
http://jsfiddle.net/vol7ron/Z7HDn/
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