0

这可能是一个愚蠢的问题,但有没有办法从 url 中选择 css id?例如在这样的网址中:

www.website.com#adiv

使用#adivJavascript/jQuery?

编辑

到目前为止我的脚本:

$(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>
4

1 回答 1

8

那将是window.location.hash

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

或者直接

$(window.location.hash).addClass(...);
于 2012-10-13T00:29:15.527 回答