简体   繁体   English

动态CSS类jQuery

[英]Dynamic css class jQuery

I want the link to have a different style on page load. 我希望链接在页面加载时具有不同的样式。 For example, if I click the About Us menu item and go to the page I want it show as highlighted to let the user know they are on that page Using jQuery. 例如,如果单击“ About Us菜单项,然后转到该页面,则该页面将突出显示,以使用户知道他们在使用jQuery的页面上。

I have tried the following code: 我尝试了以下代码:

$("#navigation").click(function()
{
    $('li').addClass('current-menu-item');
});

After triggering 'About Us', your link will change class, but when page will load, all js changes will disappear. 触发“关于我们”后,您的链接将更改类,但是在加载页面时,所有js更改都将消失。 You need change class not on click, but onload page, based on your location 您需要基于位置的更改类,而不是单击,而是在加载页面上

$(function() {
    if (window.location == '/about') // change about to what you page on
        $('#navigation li a[href=/about]').parent().addClass('current-menu-item'); // change here link too
});

If you have a list 如果您有清单

On the Server side you'll want to keep track which page you are on. 在服务器端,您需要跟踪您所在的页面。 There are many ways you could do this but one way is 您可以通过多种方式执行此操作,但是一种方法是

<ul>
    <li data-link="home">Home</li>
    <li data-link="about">About Us</li>
    <li data-link="contact>Contact</li>
</ul>

and if using php for example 并且如果使用php为例

$(document).ready(function() {
    var currentPage = "<?= $page ?>";
    $('li[data-link='+currentPage+']').addClass('current-menu-item');
});

Handling which link gets the class 'current-menu-item' is much better on the server side but for a quick example i did it using jquery. 在服务器端处理哪个链接获取类“ current-menu-item”要好得多,但是作为一个简单的例子,我使用了jQuery。

Any time you want something done on page load you can place it in $(document).ready http://api.jquery.com/ready/ 每当您希望在页面加载中完成某些操作时,都可以将其放置在$(document).ready http://api.jquery.com/ready/

Edit 编辑

One quick and easy way of setting $page is in the page requested itself so... 设置$ page的一种快速简便的方法是在自己请求的页面中,这样...

about.php about.php

<?php
    $page = "about"
?>
<html>
    ....
</html>

There are many ways of doing this so you just need to get creative. 有很多方法可以做到这一点,因此您只需要发挥创造力即可。 That's the beauty of programming :) 那就是编程的美丽:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM