How to Detect CSS Changes using JQuery
JQuery does not have a built-in event for detecting changes in CSS attributes. However, you can create your own using the following approaches:
Continuous DOM Monitoring (First Way):
Poll the DOM periodically (e.g., every 500 milliseconds) to compare the current CSS attribute value to the previous value. If they differ, trigger an event.
Example:
<code class="javascript">var $element = $("#elementId"); var lastHeight = $("#elementId").css('height'); function checkForChanges() { if ($element.css('height') != lastHeight) { alert('xxx'); lastHeight = $element.css('height'); } setTimeout(checkForChanges, 500); } checkForChanges();</code>
Manual Event Triggering (Second Way):
Bind a custom event handler to the target element, and then manually trigger this event whenever you change the element's CSS.
Example:
<code class="javascript">$('#mainContent').bind('heightChange', function(){ alert('xxx'); }); $("#btnSample1").click(function() { $("#mainContent").css('height', '400px'); $("#mainContent").trigger('heightChange'); });</code>
Determining Height Changes Specifically (Solution for Initial Problem):
In the specific case of detecting height changes for the #mainContent div, use the second approach with the following code:
<code class="javascript">$('#mainContent').bind('heightChange', function () { $("#separator").css('height', $("#mainContent").height()); });</code>
Remember to bind the event handler before making any height changes to the #mainContent div.
The above is the detailed content of How to Detect CSS Changes, Particularly Height Changes, Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!