如何在纯JavaScript中切换元素的类? [英] How do I toggle an element's class in pure JavaScript?
本文介绍了如何在纯JavaScript中切换元素的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种将jQuery代码(在响应菜单部分中使用)转换为纯JavaScript的方法。
I'm looking for a way to convert this jQuery code (which is used in responsive menu section) to pure JavaScript.
如果很难实现,那么OK使用其他JavaScript框架。
If it's hard to implement it's OK to use other JavaScript frameworks.
$('.btn-navbar').click(function()
{
$('.container-fluid:first').toggleClass('menu-hidden');
$('#menu').toggleClass('hidden-phone');
if (typeof masonryGallery != 'undefined')
masonryGallery();
});
提前感谢
推荐答案
2014答案: classList.toggle()
是大多数浏览器的标准和支持。
2014 answer: classList.toggle()
is the standard and supported by most browsers.
旧版浏览器可以使用使用classlist.js classList.toggle():
var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');
除此之外,您不应该使用ID(窗口对象中。 )。
As an aside, you shouldn't be using IDs (they leak globals into the JS window
object).
这篇关于如何在纯JavaScript中切换元素的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文