$(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>
这里我应用背景颜色来偏移父级,但我也希望它进行切换,当我单击按钮时背景颜色为红色,但是当我再次单击时应该使用切换方法更改背景颜色
最佳答案
实现此目的的最简单方法是将要添加/删除的样式放入它自己的 CSS 类中,然后调用 toggleClass()
。以这种方式将您的样式规则保留在 HTML 和 JS 代码之外(即在单独的样式表中)也是更好的做法。试试这个:
.on {
background-color: red;
}
$("button").click(function() {
$("p").offsetParent().toggleClass('on')
});
关于javascript - 切换 jquery offsetParent() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38284183/