简体   繁体   English

使用JS / Ajax通过锚动态获取URL

[英]Dynamically get URL with anchors using JS/Ajax

I have a website that based on anchors. 我有一个基于锚的网站。

For ex. 对于前。 the default URL is domain.com . 默认URL为domain.com

Another section of this website has the URL domain.com/#section1 . 该网站的另一部分包含URL domain.com/#section1

One more section has the URL domain.com/#section2 . URL的另一部分是domain.com/#section2

When I tried to get the full URL of webiste I used 当我尝试获取Webiste的完整URL时,我使用了

window.location.href window.location.href

but when I scroll down my page and the URL changed to domain.com/#section1 my window.location.href didn't change. 但是当我向下滚动页面并且URL更改为domain.com/#section1我的window.location.href并没有改变。

My JS: 我的JS:

$anchor = window.location.hash;

    if($anchor == "#kraftwerk-82"){
        $(".starting-logo.default-logo").attr("src","/logo_main.png");
        $(".starting-logo.default-logo").attr("srcset","/logo_main.png 1x, /retina_logo.png 2x");
    }else{
        $(".starting-logo.default-logo").attr("src","/logo_main_white.png");
        $(".starting-logo.default-logo").attr("srcset","/logo_main_white.png 1x, /retina_logo_white.png 2x");
    }

How can I dynamically get the URL with right anchor using JS? 如何使用JS使用正确的锚点动态获取URL?

You can use window.location.hash for get only the hash tag: 您可以使用window.location.hash仅获取hash标签:

yourHash = window.location.hash.substring(1)

UPDATE UPDATE

if(window.location.hash){
    console.log(window.location.href + window.location.hash);
}else{
    console.log(window.location.href);
}

UPDATE II 更新二

When you scroll you need to change the hash. 滚动时,您需要更改哈希。 example: 例:

var anchor_top = $('a[href="#kraftwerk-82"]').offset().top;

$(window).on('scroll', function() {
    if ( $(window).scrollTop() > anchor_top ) {
        window.location.hash = '#kraftwerk-82';
    }
});

And on function called you can check what is the hash now: 在调用的函数上,您现在可以检查什么是哈希:

Function track(){
    $anchor = window.location.hash;
    if($anchor == "#kraftwerk-82"){
        $(".starting-logo.default-logo").attr("src","/logo_main.png");
        $(".starting-logo.default-logo").attr("srcset","/logo_main.png 1x, /retina_logo.png 2x");
    }else{
        $(".starting-logo.default-logo").attr("src","/logo_main_white.png");
        $(".starting-logo.default-logo").attr("srcset","/logo_main_white.png 1x, /retina_logo_white.png 2x");
    }
}

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

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