javascript 如何让 class="selected" 取决于当前页面/url 是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15774962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:03:57  来源:igfitidea点击:

How to have the class="selected" depending on what the current page/url is

phpjavascriptcsshtml

提问by GitKidd

This is my first post so forgive as I am just new in the world of web development.

这是我的第一篇文章,请原谅,因为我只是 Web 开发领域的新手。

Normally, when I try to make a website, I create a file called header.html and footer.html so that I only change data once in all of the pages rather than having multiple same headers on many html files. And include them all in a php file together with the content and the php codes that comes per page.

通常,当我尝试制作网站时,我会创建一个名为 header.html 和 footer.html 的文件,以便我只在所有页面中更改一次数据,而不是在许多 html 文件上有多个相同的标题。并将它们与每页的内容和 php 代码一起包含在一个 php 文件中。

Now my problem is because I only have 1 header, the css is designed in a way that whatever the current menu/tab is, it will be marked as "selected" so that its obvious to the user what page they are currently in.

现在我的问题是因为我只有 1 个标题,css 的设计方式是无论当前菜单/选项卡是什么,它都会被标记为“已选择”,以便用户可以清楚地看到他们当前所在的页面。

My question is how do I solve this problem:

我的问题是如何解决这个问题:

1.) To have the class="selected"depending on what the current page/url is.

1.)class="selected"取决于当前页面/url 是什么。

<!--Menu Starts-->
        <div class="menu">
            <div id="smoothmenu" class="ddsmoothmenu">
                <ul>
                    <li><a href="index.php" class="selected">Home</a></li>
                    <li><a href="about.php">About</a> </li>
                    <li><a href="services.php">Services</a> </li>
                    <li><a href="features.php">Features</a></li>
                    <li><a href="#">Support</a>
                        <ul>
                            <li><a href="support1.php">Support 1</a></li>
                            <li><a href="support2.php">Support 2</a></li>
                         </ul>
                    </li>
                </ul>
             </div>
        </div>
<!-- Menu Ends--!>

Thank You :)

谢谢 :)

回答by Chris Moutray

If you're looking for a non-javascript / php approach...

如果您正在寻找非 javascript / php 方法...

First you need to determine which nav-link should be set as active and then add the selectedclass. The code would look something like this

首先,您需要确定应将哪个导航链接设置为活动,然后添加选定的类。代码看起来像这样

HTML within php file

php 文件中的 HTML

Call a php function inline within the hyperlink <a>markup passing in the links destination request uri

<a>传递链接目标请求 uri的超链接标记中内联调用 php 函数

<ul>
    <li><a href="index.php" <?=echoSelectedClassIfRequestMatches("index")?>>Home</a></li>
    <li><a href="about.php" <?=echoSelectedClassIfRequestMatches("about")?>>About</a> </li>
    <li><a href="services.php" <?=echoSelectedClassIfRequestMatches("services")?>>Services</a> </li>
    <li><a href="features.php" <?=echoSelectedClassIfRequestMatches("features")?>>Features</a></li>
    <li><a href="#">Support</a>
        <ul>
            <li><a href="support1.php" <?=echoSelectedClassIfRequestMatches("support1")?>>Support 1</a></li>
            <li><a href="support2.php" <?=echoSelectedClassIfRequestMatches("support2")?>>Support 2</a></li>
         </ul>
    </li>
</ul>

PHP function

PHP函数

The php function simply needs to compare the passed in request uri and if it matches the current page being rendered output the selectedclass

php 函数只需要比较传入的请求 uri,如果它匹配当前呈现的页面,则输出选定的

<?php
function echoSelectedClassIfRequestMatches($requestUri)
{
    $current_file_name = basename($_SERVER['REQUEST_URI'], ".php");

    if ($current_file_name == $requestUri)
        echo 'class="selected"';
}
?>

回答by Rick Calder

Give each link a separate id then use jQuery on the individual pages.

给每个链接一个单独的 id,然后在各个页面上使用 jQuery。

 <li><a href="index.php" id="home">Home</a></li>
 <li><a href="about.php" id="about">About</a> </li>
 <li><a href="services.php" id="services">Services</a> </li>
 <li><a href="features.php" id="features">Features</a></li>
 <li><a href="#" id="support">Support</a>
     <ul>
         <li><a href="support1.php">Support 1</a></li>
         <li><a href="support2.php">Support 2</a></li>
     </ul>
 </li>

On the services page:

在服务页面:

$(document).ready(function(){
    $("#services").addClass("selected");
});

Or even better as robertc pointed out in the comments, there is no need to even bother with the id's just make the jquery this:

或者甚至更好,正如 robertc 在评论中指出的那样,甚至不需要打扰 id,只需将 jquery 设置为:

$(document).ready(function(){
    $("[href='services.php']").addClass("selected");
});

回答by ajtrichards

You could ID each link and use JavaScript/Jquery to add the selectedclass to the appropriate link.

您可以识别每个链接并使用 JavaScript/Jquery 将selected类添加到适当的链接。

<!--Menu Starts-->
        <div class="menu">
            <div id="smoothmenu" class="ddsmoothmenu">
                <ul>
                    <li id="home-page"><a href="index.php" class="selected">Home</a></li>
                    <li id="about-page"><a href="about.php">About</a> </li>
                    <li id="services-page"><a href="services.php">Services</a> </li>
                    <li id="features-page"><a href="features.php">Features</a></li>
                    <li id="support-page"><a href="#">Support</a>
                        <ul>
                            <li id="support1-page"><a href="support1.php">Support 1</a></li>
                            <li id="support2-page"><a href="support2.php">Support 2</a></li>
                         </ul>
                    </li>
                </ul>
             </div>
        </div>
<!-- Menu Ends--!>

On your content page use jQuery to do something like:

在您的内容页面上,使用 jQuery 执行以下操作:

$(document).ready(function(){
    $("#features-page").addClass("selected");
});

Another method you could use is:

您可以使用的另一种方法是:

Add class element based on the name of the page

根据页面名称添加class元素

回答by Matt Gibson

One variant on Chris's approach is to output a particular class to identify the page, for example on the bodyelement, and then use fixed classes on the menu items, and a CSS rule that targets them matching. For example, this page:

Chris 方法的一个变体是输出一个特定的类来标识页面,例如在body元素上,然后在菜单项上使用固定类,以及针对它们匹配的 CSS 规则。例如,这个页面:

<DOCTYPE HTML>
<head>
  <title>I'm the about page</title>
  <style type="text/css">
         .about .about,
         .index .index,
         .services .services,
         .features .features {
           font-weight: bold;
         }
  </style>
</head>
<body class="<?php echo basename(__FILE__, ".php"); ?>">
  This is a menu:
  <ul>
    <li><a href="index.php" class="index">Home</a></li>
    <li><a href="about.php" class="about">About</a> </li>
    <li><a href="services.php" class="services">Services</a> </li>
    <li><a href="features.php" class="features">Features</a></li>
  </ul>
</body>

...is pretty light on dynamic code, but should achieve the objective; if you save it as "about.php", then the About link will be bold, but if you save it as "services.php", then the Services link will be bold, etc.

...对动态代码非常了解,但应该可以达到目标;如果将其保存为“about.php”,则“关于”链接将为粗体,但如果将其保存为“services.php”,则“服务”链接将为粗体,等等。

If your code structure suits it, you might be able to simply hardcode the page's bodyclass in the page's template file, rather than using any dynamic code for it. This approach effectively gives you a way of moving the "logic" for the menu system out of the menu code, which will always remain the same for every page, and up to a higher level.

如果您的代码结构适合它,您也许可以简单地body在页面的模板文件中硬编码页面的类,而不是使用任何动态代码。这种方法有效地为您提供了一种将菜单系统的“逻辑”移出菜单代码的方法,菜单代码对于每个页面始终保持相同,并一直保持到更高级别。

As an added bonus, you can now use pure CSS to target other things based on the page you're on. For example, you could turn all the h1elements on the index.phppage red just using more CSS:

作为额外的好处,您现在可以使用纯 CSS 来根据您所在的页面定位其他内容。例如,您可以使用更多 CSSh1index.php页面上的所有元素变为红色:

 .index h1 { color: red; }

回答by adnanmn

You can do it from simple if and PHP page / basename() function..

您可以通过简单的 if 和 PHP 页面 / basename() 函数来实现。

<!--Menu Starts-->
    <div class="menu">
        <div id="smoothmenu" class="ddsmoothmenu">
            <ul>
                <li><a href="index.php" <?php if (basename($_SERVER['PHP_SELF']) == "index.php") { ?> class="selected" <?php } ?>>Home</a></li>
                <li><a href="about.php" <?php if (basename($_SERVER['PHP_SELF']) == "about.php") { ?> class="selected" <?php } ?>>About</a> </li>
                <li><a href="services.php" <?php if (basename($_SERVER['PHP_SELF']) == "services.php") { ?> class="selected" <?php } ?>>Services</a> </li>
                <li><a href="features.php" <?php if (basename($_SERVER['PHP_SELF']) == "features.php") { ?> class="selected" <?php } ?>>Features</a></li>
            </ul>
         </div>
    </div>

回答by Umair Hamid

Sorry for my bad English, however may be it could help. You can use jQuery for this task. For this you need to match the page url to the anchor of menu and then add class selected to it. for example the jQuery code would be

对不起,我的英语不好,但可能会有所帮助。您可以将 jQuery 用于此任务。为此,您需要将页面 url 与菜单的锚点相匹配,然后向其中添加选择的类。例如 jQuery 代码将是

    jQuery('[href='+currentURL+']').addClass('selected');