简体   繁体   中英

Change css of inner div when outer div's css change

I would like to know if there is a way to change a div's style when the style of another div changes.

Let's say for example that we have a div (test1), that changes its z-index after 5 sec. I would like to change the css of another div (test2) when test1 has z-index=2 .

I don't think there are built in events for that, but you could use a setInterval like this:

 var divStyle = null; setInterval(function () { var newDivStyle = $("#myDiv").attr("style"); if (newDivStyle !== divStyle) { divStyle = newDivStyle; $("#myDiv").trigger("divStyleChange"); } }, 50); $("#myDiv").bind("divStyleChange", function () { $("#myDiv2").css("background-color", "#"+((1<<24)*Math.random()|0).toString(16)); }); function ChangeColorOfOuterDiv() { $('#myDiv').css('background-color','#'+((1<<24)*Math.random()|0).toString(16)); } 
 #myDiv { width:100px; height:100px; background-color:red; } #myDiv2 { width:50px; height:50px; background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myDiv"> <div id="myDiv2"></div> </div> <button onClick="ChangeColorOfOuterDiv()">Change color of outer div</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM