創新實訓(十)——程式碼美化部分:導航欄的active

山城甘草發表於2024-06-23

程式碼美化部分————導航欄的active

對於導航欄來說,當選定在某個功能部分時,當前模組會有高亮顯示。

檢視main-nav.php中有管導航欄的程式碼

<div class="collapse navbar-collapse" id="navbarSupportedContent">
		<ul class="nav nav-pills main-nav mr-auto">
			<li class="nav-item <?php echo Algo::isPrefix($_SERVER['REQUEST_URI'], '/contest'); ?>"><a class="nav-link" href="<?= HTML::url('/contests') ?>"><span class="glyphicon glyphicon-stats"></span> <?= UOJLocale::get('contests') ?></a></li>
			<li class="nav-item <?php echo Algo::isPrefix($_SERVER['REQUEST_URI'], '/problem'); ?>"><a class="nav-link" href="<?= HTML::url('/problems') ?>"><span class="glyphicon glyphicon-list-alt"></span> <?= UOJLocale::get('problems') ?></a></li>
			<li class="nav-item <?php echo Algo::isPrefix($_SERVER['REQUEST_URI'], '/submission'); ?>"><a class="nav-link" href="<?= HTML::url('/submissions') ?>"><span class="glyphicon glyphicon-tasks"></span> <?= UOJLocale::get('submissions') ?></a></li>
			<li class="nav-item <?php echo Algo::isPrefix($_SERVER['REQUEST_URI'], '/blog'); ?>"><a class="nav-link" href="<?= HTML::blog_list_url() ?>"><span class="glyphicon glyphicon-edit"></span> <?= UOJLocale::get('blogs') ?></a></li>
			<li class="nav-item <?php echo Algo::isPrefix($_SERVER['REQUEST_URI'], '/faq'); ?>"><a class="nav-link" href="<?= HTML::url('/faq') ?>"><span class="glyphicon glyphicon-info-sign"></span> <?= UOJLocale::get('help') ?></a></li>
		</ul>
	</div>

首先,對於高亮部分,使用class = active的標籤進行使用。查詢當前路由資訊的字串字首是否和給出的字串相同。具體程式碼如下:

class Algo {
    public static function isPrefix($strA, $strB) {
        $prefix = substr($strA, 0, strlen($strB));
        if (strcmp($prefix, $strB) === 0) {
            return 'active';
        } else {
            return '';
        }
    }
}

對於class = active,採用如下css程式碼去渲染

# 顏色,圓角設定
ul.main-nav>li.active {
    background-color: lightblue;
    border-radius: 10px;
}

# 字型設定
ul.main-nav>li.active>a {
    color: white;
}

ul.main-nav>li>a {
    color: black;
}

form {
    justify-content: space-evenly;
}

注意,該程式碼存放在hakuro-nav.css檔案中,必須在header中放在最後一個去渲染。

相關文章