添加/删除类onclick与JavaScript没有图书馆
我正在开发一个移动网站,并希望使用JS只是添加和删除类。 因此,为了保持良好和轻松,我不想使用jQuery。
我有以下HTML:
以及到目前为止的以下JS:
window.onLoad = init; function init() { document.getElementById('openPrimaryNav').onClick = openPrimaryNav(); document.getElementById('closePrimaryNav').onClick = closePrimaryNav(); } function openPrimaryNav() { document.getElementById('primaryNav').className = 'open'; } function closePrimaryNav() { document.getElementById('primaryNav').className = ''; }
我不能让这个工作有人能告诉我我做错了什么吗? 提前谢谢了。
基于下面提供的答案的正确JS:
window.onload = init; function init() { document.getElementById('openPrimaryNav').onclick = openPrimaryNav; document.getElementById('closePrimaryNav').onclick = closePrimaryNav; } function openPrimaryNav() { document.getElementById('primaryNav').setAttribute('class','open'); } function closePrimaryNav() { document.getElementById('primaryNav').setAttribute('class',''); }
您可以使用setAttribute
。
window.onload = init; function init() { document.getElementById('openPrimaryNav').onclick = openPrimaryNav; document.getElementById('closePrimaryNav').onclick = closePrimaryNav; } function openPrimaryNav() { document.getElementById('primaryNav').setAttribute('class','open'); } function closePrimaryNav() { document.getElementById('primaryNav').setAttribute('class',''); }
它是.onclick
,而不是.onClick
- JQuery addclass选择div,如果选择了另一个div,则删除class
- 延迟addclass / remove类函数不起作用
- addClass()然后单击removeClass()(jquery)
- 如何在JQuery中向同一个类添加不同的类?
- 分组(); 和next(); 用法澄清Jquery
- JQuery将类添加到克隆元素
- jQuery addClass似乎无法在Internet Explorer中运行
- 如何使用jQuery或JavaScript基于当前URL和单击事件将一个类“active”分配给li元素
- jQuery onclick addclass / removeclass并添加淡入淡出