3 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
好的,我會(huì)告訴你如何實(shí)現(xiàn)你想要的(2 種方法),然后我會(huì)解釋你的代碼是如何工作的。
方法一
在您的第一個(gè) div ( #wrapper) 中,添加類menuDisplayed:
<div id="wrapper" class="menuDisplayed">
方法二
您還可以更改您的 CSS 以執(zhí)行您想要的操作,并使“顯示的菜單”成為默認(rèn)樣式:
在整個(gè)代碼中將“menuDisplayed”替換為“menuHidden”,使其在語義上繼續(xù)有意義
更新樣式以#sidebar-wrapper賦予其寬度 0 以外的值。
#sidebar-wrapper{
z-index: 1;
position: fixed;
width: 250px;
height: 100%;
overflow-y: hidden;
transition: 0.15s;
background-color: var(--black) ;
font-size: 1em;
}
現(xiàn)在也更改樣式#page-content-wrapper,以便為側(cè)邊欄留出空間:
#page-content-wrapper{
width: 100%;
position: absolute;
padding: 15px;
padding-left: 250px; /* leaving 250px of space on the left */
transition: 0.15s;
color: black;
}
下一步是使封閉的側(cè)邊欄具有正確的樣式:
#wrapper.menuHidden #sidebar-wrapper{
width: 0; /* the element of id 'wrapper' and class 'menuHidden' must have width 0 */
}
#wrapper.menuHidden #page-content-wrapper {
padding-left: unset; /* clears the attribute that gave space to the sidebar */
}
現(xiàn)在我將解釋您的代碼是如何工作的(在您更改側(cè)邊欄行為之前):
你的 CSS 告訴瀏覽器帶有sidebar-wrapperid 的元素應(yīng)該有空寬度(所以它不會(huì)在你加載頁面后立即出現(xiàn)),但它也說帶有 id 的元素sidebar-wrapper在另一個(gè)元素內(nèi)部時(shí)應(yīng)該是 250px 寬wrapperid 和menuDisplayed班級(jí)。
menuDisplay魔法就在你的 javascript 中:它告訴瀏覽器用id切換元素的類wrapper,這會(huì)激活 CSS 樣式,使你的側(cè)邊欄寬 250 像素,然后它就會(huì)出現(xiàn)。再次切換時(shí),menuDisplayed該類將從具有 id 的元素中刪除,wrapper并且您的側(cè)邊欄返回寬度等于 0。
使用 jQuery為$("#menu-toggle").click“click”事件添加事件偵聽器。當(dāng)這個(gè)事件被觸發(fā)時(shí)(有人點(diǎn)擊了帶有 id 的元素menu-toggle),回調(diào)函數(shù)被執(zhí)行:
function(e){
e.preventDefault(); // prevents the default behavior of the element (if it is an anchor (<a></a>), it loses the ability to change pages, etc.)
$("#wrapper").toggleClass("menuDisplayed"); // toggles the class 'menuDisplayed' of the element with id 'wrapper'
}

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
您最初可以將類添加menuDisplayed
到導(dǎo)航欄(使用 id #wrapper
),因此在頁面加載時(shí),它將被顯示。
<div id="wrapper" class="menuDisplayed">

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
您應(yīng)該將課程添加menuDisplayed
到您的#wrapper
. 然后它可以默認(rèn)顯示。
<div id="wrapper" class="menuDisplayed">
完整的例子可以在這里找到:http: //jsfiddle.net/9ojvnutc/
添加回答
舉報(bào)