如果元素具有“活动”类,我正在寻找解决方案,是否可以将onclick值更改为“ closeSideBar”?
function openSidebar() {
document.getElementById('sidebar').style.width = '250px';
document.getElementById('hamburger').style.marginLeft = '250px'
}
function closeSideBar() {
document.getElementById('sidebar').style.width = '0';
document.getElementById('hamburger').style.marginLeft = '0'
}
<button id="hamburger" onclick="openSidebar()">
我正在寻找一种解决方案,如何获得此结果?
<button id="hamburger" onclick="closeSideBar()" class="active">
您不想更改属性值。您只想调用一个函数并指示其行为。
代替单独的打开/关闭功能,请使用一个:
function toggleSidebar(el) {
if (el.classList.contains('active')) {
document.getElementById('sidebar').style.width = '0';
document.getElementById('hamburger').style.marginLeft = '0'
} else {
document.getElementById('sidebar').style.width = '250px';
document.getElementById('hamburger').style.marginLeft = '250px'
}
}
然后调用函数,传递元素:
<button id="hamburger" onclick="toggleSidebar(this)" class="active">
提示:不要直接操作样式。而是切换类,以便您可以在样式表中的一个位置更改侧边栏的大小和位置:
function toggleSidebar(el) {
if (el.classList.contains('active')) {
document.body.classList.remove('sidebar-in');
} else {
document.body.classList.add('sidebar-in');
}
}
现在您可以使用后代选择器设置样式:
body .sidebar { ... }
body.sidebar-in .sidebar { ... }
我认为您只需要一个函数toggleSidebar
。
function toggleSidebar() {
const isActive = document.getElementById('hamburger').classList.contains('active');
if (isActive) {
closeSideBar();
} else {
openSidebar();
}
}
function openSidebar() {
document.getElementById('sidebar').style.width = '250px';
document.getElementById('hamburger').style.marginLeft = '250px';
}
function closeSideBar() {
document.getElementById('sidebar').style.width = '0';
document.getElementById('hamburger').style.marginLeft = '0';
}