$(document).ready(function(){
$("button").click(function(){
$("p").offsetParent().css("background-color", "red");
});
});
<button>Set background-color</button>
<div style="border:1px solid black;width:70%;position:absolute;left:10px;top:50px">
<div style="border:1px solid black;margin:50px;background-color:yellow">
<p>Click button to set the background color of the first positioned parent element of this paragraph.</p>
</div>
</div>
Here I am appling background color to offset parent but I want it too make toggle ,when ever I click button background color red is coming but when ever I click again that background color should be change by using toggle method
The simplest way to achieve this is to put the style you want to add/remove in to it's own CSS class and then call toggleClass()
. It's also much better practice to keep your styling rules out of the HTML and JS code (ie. in a separate stylesheet) in this manner. Try this:
.on {
background-color: red;
}
$("button").click(function() {
$("p").offsetParent().toggleClass('on')
});
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.