2013-11-03 3 views
1

Здравствуйте, я пытаюсь сделать панель навигации активной в php, чтобы пользователь мог узнать, на какой странице они находятся. Я новичок в php и не знаю много об этом. Итак, как я могу добавить class = "active" в этот код, чтобы создать активную панель навигации и отобразить всю страницу на той же странице index.php.Как сделать активную панель навигации в php?

<a href="?page=home"> Home</a></br> 
<a href="?page=news"> News</a></br> 
<a href="?page=about"> About</a></br> 
<a href="?page=contact"> Contact</a></br> 

<?php 
if (!isset($_GET['page'])) { 
    include "home.php"; 
} else { 
switch ($_GET['page']) { 
    case "home": 
     include "home.php"; 
    break; 
    case "news": 
     include "news.php"; 
    break; 
    case "about": 
     include "about.php"; 
    break; 
    case "contact": 
     include "contact.php"; 
    break; 
    default: 
     include "home.php"; 
    }; 
} 
?> 

ответ

1

Создание массива элементов меню, а затем использовать foreach цикл для создания меню динамически.

Таким образом, при добавлении новых элементов в массиве они будут отображаться в меню:

<html> 
<head> 
    <title>Website</title> 

    <style type="text/css" media="screen"> 
     .active { 
      font-weight: bold; 
     } 
    </style> 
</head> 
<body> 

<?php 

// This is your menu 
$items = array("home", "news", "about", "contact"); 

foreach ($items as $item) 
{ 
    if (isset($_GET['page']) && $_GET['page'] == $item) 
    { 
     echo '<a href="?page=' . $item . '" class="active"> ' . $item . '</a></br>'; 
     $activePage = $item . ".php"; 
    } 
    else 
    { 
     echo '<a href="?page=' . $item . '"> ' . $item . '</a></br>'; 
    } 
} 

// Include your page 
if (isset($activePage)) 
{ 
    include $activePage; 
} 
else 
{ 
    include "home.php"; 
} 

?> 

</body> 
</html> 

Вы должны заменить весь свой код с этим кодом и дать ему спину. Использование циклов для уменьшения количества избыточной разметки вам нужно написать не только DRY, но и сэкономит вам много времени в будущем!

+0

Он бросает ошибку в строке 7. «Undefined индекс: страница» –

+0

@ sn0w Ну это немного неудобно. Я отредактировал указанное выше объявление, добавив некоторую структуру HTML, чтобы поместить его в контекст. – gillytech

+0

У меня есть вторая страница с ошибками, если я дважды нажал на ту же ссылку, что и ее страница с сообщением не найдена. Скажем, если бы я нажал на новости сначала, он покажет страницу новостей, но если я снова нажму на нее, страница не будет найдена. –

1

Вы можете использовать PHP-код ниже в качестве навигации. Я рекомендую вам использовать неупорядоченный список (т.е. <ul><li><a href=""></a></li></ul>) теги для навигации:

<ul> 
    <li<?php if($_GET['page']=="home") { echo " class=\"active\""; } ?>><a href="?page=home"> Home</a></li> 
    <li<?php if($_GET['page']=="news") { echo " class=\"active\""; } ?>><a href="?page=news"> News</a></li> 
    <li<?php if($_GET['page']=="about") { echo " class=\"active\""; } ?>><a href="?page=about"> About</a></li> 
    <li<?php if($_GET['page']=="contact"){ echo " class=\"active\""; } ?>><a href="?page=contact"> Contact</a></li> 
</ul> 

Затем добавьте ниже стиль CSS:

.active { 
    font-weight: bold; 
} 
0

Попробуйте этот код:

<section id="section1"> 
     <h2>London1</h2> 
     <p> 
      London is the capital city of England. It is the most populous city in the United Kingdom, 
     with a metropolitan area of over 13 million inhabitants. 
     </p> 
     <p> 
      Standing on the River Thames, London has been a major settlement for two millennia, 
      its history going back to its founding by the Romans, who named it Londinium. 
     </p> 
    </section> 


    <section id="section2" style="display:none"> 
     <h2>London2</h2> 
     <p> 
      London is the capital city of England. It is the most populous city in the United Kingdom, 
     with a metropolitan area of over 13 million inhabitants. 
     </p> 
     <p> 
      Standing on the River Thames, London has been a major settlement for two millennia, 
      its history going back to its founding by the Romans, who named it Londinium. 
     </p> 
    </section> 


    <section id="section3" style="display:none"> 
     <h2>London3</h2> 
     <p> 
      London is the capital city of England. It is the most populous city in the United Kingdom, 
     with a metropolitan area of over 13 million inhabitants. 
     </p> 
     <p> 
      Standing on the River Thames, London has been a major settlement for two millennia, 
      its history going back to its founding by the Romans, who named it Londinium. 
     </p> 
    </section> 
    <?php include 'footer.php'; ?> 

    <script type="text/javascript"> 
    $(document).ready(function(){ 
     $("#1").click(function(){ 
      $("#section1").show(); 
      $("#section2").hide(); 
      $("#section3").hide(); 
     }); 

     $("#2").click(function(){ 
      $("#section1").hide(); 
      $("#section2").show(); 
      $("#section3").hide(); 
     }); 

     $("#3").click(function(){ 
      $("#section1").hide(); 
      $("#section2").hide(); 
      $("#section3").show(); 
     }); 
    }) 



    </script> 
-1
<div id="nav"> 
    <button id="1">London1</button><br> 
    <button id="2">2</button><br> 
    <button id="3">3</button><br> 
</div> 
<div id="nav"> 
    <a href="index.php">paris1</a><br> 
    <a href="paris.php">pzris2</a><br> 
    <a href="tokyo.php">paris3</a><br> 
</div> 
<?php include 'header.php'; ?> 
<?php include 'nav1.php'; ?> 

<?php include 'footer.php'; ?> 
+0

Я не совсем уверен, как вы ожидаете, что это сработает. –

Смежные вопросы