onhashchange with IE 9

前端 未结 3 758
春和景丽
春和景丽 2021-01-14 06:30

I have the following code

$(document).ready(function() {
   if (\"onhashchange\" in window) {
      alert(\"The browser supports the hashchange event!\");
           


        
相关标签:
3条回答
  • 2021-01-14 07:13

    See this: link

    Does the browser support window.onhashchange?

    Note that IE8 running in IE7 compatibility mode reports true for 'onhashchange' in window, even though the event isn't supported, so also test document.documentMode.

    var docmode = document.documentMode;
    if ('onhashchange' in window && (docmode === undefined || docmode > 7 )) {
        window.onhashchange = checkHash;
    }
    
    0 讨论(0)
  • 2021-01-14 07:19

    The new hashchange event in HTML5 is supported by all current browsers; no need to fool your browser into thinking it's IE8.

    This code works in IE 9, FF 5, Safari 5, and Chrome 12 on Win 7:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <script>
                window.onhashchange = doThisWhenTheHashChanges;
    
                function changeTheHash()
                {
                    var newHashValue = document.getElementById("newHashInput").value;
                    var currentLocation = window.location.pathname;
                    window.location.hash = newHashValue;
                }
    
                function doThisWhenTheHashChanges()
                {
                    alert("The hash has changed!");
                }
            </script>
        </head>
        <body> 
            <h1>Hash Change Test</h1>
            <form>
                <input type="text" id="newHashInput" autofocus>
                <input type="button" value="Set" onclick="changeTheHash()">
            </form>
        </body>
    </html>
    
    0 讨论(0)
  • 2021-01-14 07:24

    There's an example on the MSDN doc page.

    Basically, I removed all the extra "map" stuff on their page and the only difference between theirs and your example is that they include the following meta-tag:

    <meta http-equiv="X-UA-Compatible" content="IE=8" >
    

    I added this to the head tag in your example and it worked fine.

    This meta-tag basically says to run the page as if it were in IE 8 and not IE 9 (which is still in beta).

    For more information on this meta-tag read here

    0 讨论(0)
提交回复
热议问题