这篇文章主要介绍javascript中.toggleClass()怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
如果匹配元素的父级元素有bar样式类名,这个例子将为<div class="foo">元素切换 happy 样式类; 否则他将切换 sad 样式类 。
例子:
Example: 当点击段落的是有切换 'highlight' 样式类
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { color:blue; }
.highlight { background:yellow; }
</style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p class="blue">Click to toggle</p>
<p class="blue highlight">highlight</p>
<p class="blue">on these</p>
<p class="blue">paragraphs</p>
<script>
$("p").click(function () {
$(this).toggleClass("highlight");
});
</script>
</body>
</html>
Example: 每当第三次点击段落的时候添加 "highlight" 样式类, 第一次和第二次点击的时候移除 "highlight" 样式类
<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { color:blue; }
.highlight { background:red; }
</style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p class="blue">Click to toggle (<span>clicks: 0</span>)</p>
<p class="blue highlight">highlight (<span>clicks: 0</span>)</p>
<p class="blue">on these (<span>clicks: 0</span>)</p>
<p class="blue">paragraphs (<span>clicks: 0</span>)</p>
<script>
var count = 0;
$("p").each(function() {
var $thisParagraph = $(this);
var count = 0;
$thisParagraph.click(function() {
count++;
$thisParagraph.find("span").text('clicks: ' + count);
$thisParagraph.toggleClass("highlight", count % 3 == 0);
});
});
</script>
</body>
</html>
Example: Toggle the class name(s) indicated on the buttons for each div.
<!DOCTYPE html>
<html>
<head>
<style>
.wrap > div { float: left; width: 100px; margin: 1em 1em 0 0;
padding=left: 3px; border: 1px solid #abc; }
div.a { background-color: aqua; }
div.b { background-color: burlywood; }
div.c { background-color: cornsilk; }
</style>
<script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div class="buttons">
<button>toggle</button>
<button class="a">toggle a</button>
<button class="a b">toggle a b</button>
<button class="a b c">toggle a b c</button>
<a href="#">reset</a>
</div>
<div class="wrap">
<div></div>
<div class="b"></div>
<div class="a b"></div>
<div class="a c"></div>
</div>
<script>
var cls = ['', 'a', 'a b', 'a b c'];
var divs = $('div.wrap').children();
var appendClass = function() {
divs.append(function() {
return '<div>' + (this.className || 'none') + '</div>';
});
};
appendClass();
$('button').bind('click', function() {
var tc = this.className || undefined;
divs.toggleClass(tc);
appendClass();
});
$('a').bind('click', function(event) {
event.preventDefault();
divs.empty().each(function(i) {
this.className = cls[i];
});
appendClass();
});
</script>
</body>
</html>
以上是“javascript中.toggleClass()怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!