【发布时间】:2015-01-23 05:12:09
【问题描述】:
每当 div 的高度发生变化时,我都想触发一个函数。我该怎么做?
【问题讨论】:
-
这是您问题的一个很好的例子:[stackoverflow.com/questions/9628450/… [1]:stackoverflow.com/questions/9628450/…
标签: javascript jquery
每当 div 的高度发生变化时,我都想触发一个函数。我该怎么做?
【问题讨论】:
标签: javascript jquery
一个好的方法是使用 DOM 突变来验证标记特定部分的每一个变化。
例如,您可以使用jQuery mutate official plugin 来检测某物的高度是否发生变化并启动回调。
你可以试试这个:
$('div.monitor').mutate('height',function (element,info){
console.log('a div with has changed it\'s height, the function below should do something about this...');
$(this).css('background','red');
});
【讨论】:
$(document).ready(function(){
var divHeight = $("#share-something-textarea").css("height");
setInterval(function(){
if(divHeight !== $("#share-something-textarea").css("height")){
//something here
}
},200);
});
我认为您可以设置一个 setInterval 来验证每 x ms 的 div 高度。
【讨论】:
有多种方法可以实现这一点,无论如何我认为这个解决方案是迄今为止最好的。 有一个名为 Jquery Mutate 的 Jquery 库专为此类事情而创建。
(当前支持的事件:width、height、top、right、left、bottom、hide、show、scrollHeight、scrollWidth、scrollTop、scrollLeft)。
如果您希望每次 div 的高度发生变化时触发一个函数,您可以执行以下操作:
首先导入库:
<script src="http://www.google.com/jsapi"></script>
<script> google.load("jquery",'1.7'); google.load("jqueryui", "1"); </script>
<script src="mutate.events.js"></script>
<script src="mutate.min.js"></script>
那么你就可以使用这个代码了:
$('#div').mutate('height',function (element,info){
console.log('a div changed it\'s height, the function below should do something about this...');
$(this).css('background','red'); <-- example of action triggered after the event height changed
});
这里有Jquery Mutate的官网:http://www.jqui.net/jquery-projects/jquery-mutate-official/
还有一个演示,展示了它的灵活性:http://www.jqui.net/demo/mutate/
【讨论】: