選單功能是前台功能中較為複雜的一個項目,因為有主次選單的關係,很多人會在這邊搞混,要特別注意巢狀迴圈應用上容易犯錯的地方;
另外,版型檔案雖然有提供了相關的JS及CSS,但是經過測試顯示上怪怪的,因此我們會調整一下顯示次選單的方式。
記得在後台配合題目要求先將相關選單的項目先建好。
我們一樣可以先在類別中把選單的資料準備好,首頁再來做顯示的處理,也可以直接在類別中就把整個選單的html碼就準備好,先嘗試在類別中準備好資料的做法
/Controller/Menu.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function show(){
$rows=$this->all(['main_id'=>0,'sh'=>1]);
foreach($rows as $idx =>$row){
$row['subs']=$this->all(['main_id'=>$row['id']]);
$rows[$idx]=$row; }
return $rows; }
|
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <div id="menuput" class="dbor"> <!--主選單放此--> <span class="t botli">主選單區</span> <?php //執行物件中的show()方法來取得包含了次選單的主選單資料 $rows=$Menu->show(); foreach($rows as $row){ echo "<div class='mainmu'>"; echo "<a href='{$row['href']}'>";
echo $row['text']; echo "</a>";
if(!empty($row['subs'])){
echo "<div class='mw'>"; foreach($row['subs'] as $sub){ echo "<div class='mainmu2'>"; echo "<a href='{$sub['href']}'>"; echo $sub['text']; echo "</a>"; echo "</div>"; } echo "</div>"; } echo "</div>"; } ?> </div>
|
由於素材附的css沒有設定主選單的高度,我們的做法會在顯示次選單時把整個主選單撐大,
因此我們可以調整一下css中的設定,讓次選單的顯示和參考圖接近。
css/css.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| .mainmu { position:relative; border-radius:10px; background:url(../icon/menu.fw.png) center no-repeat; background-size:cover; line-height:30px; padding:2px 10px 2px 10px; margin:7px 1px 7px 1px; height:30px; }
.mw{ position: relative; top:-15px; left:75px; z-index:10; }
.mainmu a{ display:block; text-decoration:none; }
.mainmu a:hover{ text-decoration:underline; }
|