javascript 使用 jQuery 更改当前页面链接的 CSS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16027629/
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:58:56  来源:igfitidea点击:

Changing CSS for link of current page with jQuery

javascriptjquerycssdynamic

提问by Max

New coder here and would really appreciate your help with a problem that's got me stumped.

这里是新的编码员,非常感谢您对让我感到困惑的问题的帮助。

I'd like to write code that will recognize the link that applies to the current page and applies a different CSS style to that current link. I've researched this problem and have found that it's best accomplished using jQuery to identify the current link and then apply a new class to it (e.g., ".current"). However, when I've tried to implement this on the site it hasn't worked.

我想编写代码来识别适用于当前页面的链接并将不同的 CSS 样式应用于该当前链接。我研究过这个问题,发现最好使用 jQuery 来识别当前链接,然后对其应用一个新类(例如,“.current”)。然而,当我试图在网站上实现它时,它没有奏效。

This is the HTML I'm working with:

这是我正在使用的 HTML:

<nav class="main-nav">
   <a href="http://website.com" class="main-nav-link">
      <span class="main-nav-item" id="nav-content"></span>
   </a>
   <a href="http://website.com/calendar" class="main-nav-link">
      <span class="main-nav-item" id="nav-calendar"></span>
   </a>
   <a href="http://website.com/profile" class="main-nav-link">
      <span class="main-nav-item" id="nav-profile"></span>
   </a>
</nav>

And this is the CSS I've applied:

这是我应用的 CSS:

.main-nav .main-nav-item {
  height: 50px;
  width: 150px;
}

.main-nav #nav-content {
  background: url('/images/content-inactive.png') no-repeat center;
}

.main-nav #nav-calendar {
  background: url('/images/calendar-inactive.png') no-repeat center;
}

.main-nav #nav-profile {
  background: url('/images/profile-inactive.png') no-repeat center;
}

My goal is to change the background:for the span within the current page's <a>.

我的目标是更改background:当前页面的<a>.

Here are some other StackOverflow threads that have addressed this problem, but haven't helped me to reach a solution:

这里有一些其他的 StackOverflow 线程已经解决了这个问题,但没有帮助我找到解决方案:

It's not completely clear to me where I'm supposed to be putting the Javascript, but I currently have it between <script type="text/javascript">and </script>in the <header>section.

我并不完全清楚我应该将 Javascript 放在哪里,但我目前在该部分之间<script type="text/javascript">和部分中都有它。</script><header>

Thanks in advance for your assistance. :)

提前感谢你的帮助。:)

--

——

UPDATE:

更新:

I currently have the following code in the page, but it's not working.

我目前在页面中有以下代码,但它不起作用。

The Javascript:

Javascript:

<script>

      $(document).ready(function() {

     // Get the current URL
            var currentUrl = window.location.href;

            // Get the span you want with a combination class and attribute and child jQuery selector
            var currentMenuItem = $(".main-nav-link[href='" + currentUrl + "'] > .main-nav-item");

            // Then add your class
            currentMenuItem.addClass("current");

        });

</script>

And the CSS:

和 CSS:

#nav-content.current {
  background: url('/images/content-active.png') no-repeat center -94px;
}

The jQuery isn't adding the .currentclass to the active link, so the CSS doesn't even have the opportunity to work.

jQuery 没有将.current类添加到活动链接,因此 CSS 甚至没有机会工作。

采纳答案by davidtheclark

window.location.hrefwill get your current URL. Then you need to use a jQuery selector that finds the <span class="main-nav-item">child of the <a class="main-nav-link">element with that hrefattribute. Apply your class "current" to that element, and you should be good to go. So how about this JavaScript:

window.location.href将获得您当前的网址。然后,您需要使用 jQuery 选择器来查找具有该属性<span class="main-nav-item"><a class="main-nav-link">元素的子元素href。将您的类“当前”应用于该元素,您应该很高兴。那么这个 JavaScript 怎么样:

// Get the current URL
var currentUrl = window.location.href;

// Get the span you want with a combination class and attribute and child jQuery selector
var currentMenuItem = $(".main-nav-link[href='" + currentUrl + "'] > .main-nav-item");

// Then add your class
currentMenuItem.addClass("current");

Put that in your script tags and give it a try.

把它放在你的脚本标签中并试一试。

Once you have it working, make sure you add the proper CSS rules. For example, add a rule that loads a different background image for #nav-content.current(and another all the rest).

一旦你让它工作,确保你添加了正确的 CSS 规则。例如,添加一个规则,为#nav-content.current(以及其他所有)加载不同的背景图像。

(A note about your current CSS: It looks like you're overqualifying your selectors. If you don't have to worry about .main-nav-items anywhere else on the page, don't bother qualifying that class with the .main-navbefore it. And your id selectors (e.g. #nav-content) certainly don't need to be qualified, since they're unique identifiers.)

(关于您当前 CSS 的说明:看起来您对选择器的.main-nav-item限定过高。如果您不必担心页面上其他任何地方的 s,请不要费心使用.main-nav它来限定该类。还有您的 id 选择器(例如#nav-content)当然不需要限定,因为它们是唯一标识符。)

Hope that makes sense to you and helps.

希望这对您有意义并有所帮助。

回答by Jules Colle

The common way to do this, is to add a class like "active" to your active page-link server side. You could then style the element with jQuery like so:

执行此操作的常用方法是在您的活动页面链接服务器端添加一个类似“active”的类。然后你可以像这样使用 jQuery 设置元素的样式:

$('.active').css('background-image','images/activebg.png');

But as you mentioned, you would need a different background for each "active" element, and you want to use the link. (I suppose you mean the URL).

但是正如您所提到的,您需要为每个“活动”元素设置不同的背景,并且您想使用该链接。(我想你的意思是网址)。

You can get the current page's URL like this:

您可以像这样获取当前页面的 URL:

var current_url = window.location.href;

You can then select the link with the current URL like this:

然后,您可以像这样选择带有当前 URL 的链接:

var $link = $('.main-nav a[href='+current_url +']');

So now you can set the background active for the current page link like this:

所以现在您可以像这样为当前页面链接设置背景活动:

$link.css('background-image','images/activebg.png');

Now, if you have a custom active background for each link, I would suggest you create your own attribute hover_imgor something in which you provide the hover url:

现在,如果您为每个链接设置了自定义活动背景,我建议您创建自己的属性hover_img或提供悬停 url 的内容:

<a href="http://website.com" class="main-nav-link" hover_img="/images/hover-home.png" > ....
<a href="http://website.com/calendar" class="main-nav-link calendar" hover_img="/images/hover-calendar.png"> ....

and so on.

等等。

Then, you can change my last line of code to:

然后,您可以将我的最后一行代码更改为:

$link.css('background-image',$link.attr('hover_img'));

回答by tymeJV

Inside your script page tags you can use the following:

在脚本页面标签中,您可以使用以下内容:

$(document).ready(function() {
    var currentPage = "content"; // <--Change this to the id of your span after the nav-

    //Change the background color now
    $("#nav-" + currentPage).addClass("className");
});