3 回答
TA貢獻1865條經驗 獲得超7個贊
好的,我會告訴你如何實現你想要的(2 種方法),然后我會解釋你的代碼是如何工作的。
方法一
在您的第一個 div ( #wrapper) 中,添加類menuDisplayed:
<div id="wrapper" class="menuDisplayed">
方法二
您還可以更改您的 CSS 以執行您想要的操作,并使“顯示的菜單”成為默認樣式:
在整個代碼中將“menuDisplayed”替換為“menuHidden”,使其在語義上繼續有意義
更新樣式以#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;
}
現在也更改樣式#page-content-wrapper,以便為側邊欄留出空間:
#page-content-wrapper{
width: 100%;
position: absolute;
padding: 15px;
padding-left: 250px; /* leaving 250px of space on the left */
transition: 0.15s;
color: black;
}
下一步是使封閉的側邊欄具有正確的樣式:
#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 */
}
現在我將解釋您的代碼是如何工作的(在您更改側邊欄行為之前):
你的 CSS 告訴瀏覽器帶有sidebar-wrapperid 的元素應該有空寬度(所以它不會在你加載頁面后立即出現),但它也說帶有 id 的元素sidebar-wrapper在另一個元素內部時應該是 250px 寬wrapperid 和menuDisplayed班級。
menuDisplay魔法就在你的 javascript 中:它告訴瀏覽器用id切換元素的類wrapper,這會激活 CSS 樣式,使你的側邊欄寬 250 像素,然后它就會出現。再次切換時,menuDisplayed該類將從具有 id 的元素中刪除,wrapper并且您的側邊欄返回寬度等于 0。
使用 jQuery為$("#menu-toggle").click“click”事件添加事件偵聽器。當這個事件被觸發時(有人點擊了帶有 id 的元素menu-toggle),回調函數被執行:
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貢獻1873條經驗 獲得超9個贊
您最初可以將類添加menuDisplayed到導航欄(使用 id #wrapper),因此在頁面加載時,它將被顯示。
<div id="wrapper" class="menuDisplayed">
TA貢獻1906條經驗 獲得超3個贊
您應該將課程添加menuDisplayed到您的#wrapper. 然后它可以默認顯示。
<div id="wrapper" class="menuDisplayed">
完整的例子可以在這里找到:http: //jsfiddle.net/9ojvnutc/
添加回答
舉報
