【问题标题】:Get css id from url从 url 获取 css id
【发布时间】:2012-10-03 20:17:21
【问题描述】:

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

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>

【问题讨论】:

    标签: javascript css url


    【解决方案1】:

    那就是window.location.hash

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

    或者直接

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

    【讨论】:

    • 如何用 jQuery 选择它?我试过var c = window.location.hash; c.addClass('blabla');,但它不起作用。
    • $(window.location.hash).addClass('blabla'); 这实际上相当方便,因为默认情况下“哈希”包含井号,因此您可以将其直接输入到 jQuery 选择器中。
    • 我敢打赌这是因为您在页面加载之前就已经尝试过了。必须在加载所有元素时完成,即$(document).ready(function(){/*blabla*/});
    • @Jeffrey 请在您的帖子中添加其他数据,而不是在 cmets 中。
    • @JosephtheDreamer,已编辑。它在我点击时有效,但在我第一次加载 www.site.com#header 时无效。
    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2012-07-05
    • 2020-01-30
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多