我在使用Jquery时遇到一些问题。我有可调整的div。该div为绿色,如果该div大于200px,则必须将其颜色更改为红色。您能帮我,怎么做?
答案 0 :(得分:0)
您可以使用mutation observers进行此操作。 在所有主要的browsers
中似乎都提供了很好的支持它监听DOM修改。
//get your element
const targetNode = document.getElementById('container');
//listen to attribute changes on the element
const config = { attributes: true };
//create the function which changes the color
const callback = (mutationsList, observer) => {
const ele = $("#container");
const width = ele.width();
const height = ele.height();
if(width > 200 || height > 200){
ele.css("background-color", "red");
} else if(width < 200 && height < 200){
ele.css("background-color", "green");
}
};
//Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
//Start observing the target node for configured mutations
observer.observe(targetNode, config);
#container {
resize: both;
overflow: auto;
width: 100px;
height: 100px;
background-color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>