Could a page display diferrent content if the URL hash changes?

前端 未结 7 1896
名媛妹妹
名媛妹妹 2021-01-14 15:24

How could a page display different content based on the URL hash?

I\'m not talking about the browser scrolling down to display the anchored section, but something li

7条回答
  •  天命终不由人
    2021-01-14 15:57

    I just built a system to do this a few weeks ago

    depeding on the browser you need to detect the hash, heres how to do that

    // test all possible places hash could be on different browsers
    if(window.location.hash){
       hash = window.location.hash;
    } else if (document.location.hash){
       hash = document.location.hash;
    } else if (location.hash){
       hash = location.hash;
    }
    
    // some browsers start the hash with #, remove it for consistency
    if(hash.substring(0,1) == '#'){
        hash = hash.substring(1,hash.length);
    }
    

    Then handle the value of the hash variable to trigger page changes as you please.

    for example: http://www.example.com#pageA

    if(hash = 'pageA'){
      document.getElementById('mainContentDiv').innerHTML = '

    content for the page displayed when the hash sais pageA

    '; }

提交回复
热议问题