javascript - 从 url 获取 css id

标签 javascript css url

这可能是个愚蠢的问题,但有没有办法从 url 中获取 css id? 例如在这样的 url 中:

www.website.com#adiv

使用 Javascript/jQuery 获取 #adiv

编辑

到目前为止我的脚本:

$(document).ready(function() {
    var c = window.location.hash;
    $(c).addClass('current');
    $('a').click(function (){
        $('.current').removeClass('current');
        $(this).addClass('current');
    });
});

HTML:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title</title>
  <link rel="stylesheet" href="style.css">
  <script src="jquery-1.4.2.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        var c = window.location.hash;
        $(c).addClass('current');
        $('a').click(function () {
            $('.current').removeClass('current');
            $(this).addClass('current');
        });
        $('a[href*=#]').click(function() {
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
            && location.hostname == this.hostname) {
                var $target = $(this.hash);
                $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
                if ($target.length) {
                    var targetOffset = $target.offset().top;
                    $('html,body').animate({scrollTop: targetOffset}, 1000);
                    return false;
                }
            }
        });
    });
    </script>
</head>
<body>
    <nav>
        <a href="#header">First</a>
        <a href="#second">Second</a>
    </nav>
    <section id="header">
        ...
    </section>
    <section id="history">
        ...
    </section>
</body>
</html>

最佳答案

那就是 window.location.hash

var hash = window.location.hash;
$(hash).addClass(...);

或者直接

$(window.location.hash).addClass(...);

关于javascript - 从 url 获取 css id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12868830/

相关文章:

c# - 获取 Html.RouteLink 结果的 URL 地址

javascript - 当单击该表中的按钮时,如何使使用toggleClass 显示的表保持打开状态?

css - 如何使用 CSS 为子 div 设置相同的高度

javascript - 读取 URL 参数时代码未获取预期值

html - 语义 UI 片段

css - 添加/删除类时动画背景颜色向下滑动,仅使用 CSS?

java - 在 URL 和 Windows 文件名(Java)之间转换?

javascript - 为什么用 document.write 插入的脚本可以更改变量

javascript - window.open 带标题

javascript - 根据特定值按顺序显示数组中的对象