导航栏: 首页 评论列表

HTML5无刷修改URL

默认分类 2014/08/01 00:07

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5无刷修改URL</title>
<script type="text/javascript">
window.onload = function () {
    document.getElementById('status').innerHTML = Math.random();
};     

function linkClick(event, elem) {
    var d = {url: elem.href, name: elem.innerHTML, 'location': elem.href};
    window.history.pushState(d, elem.innerHTML, elem.href);
    document.getElementById('lastevent').innerHTML = event.type + ' : ' + elem.href;
    return false;
}

window.onpopstate = function (event) {
    var d = event.state || { url: "unknown", name: "undefined", 'location': "undefined" };
    document.getElementById('lastevent').innerHTML = event.type + ' : ' + event.state.url;
    document.getElementById('output').innerHTML = '<p>URL: '+d.url+'</strong>, name: '+d.name+', location: '+d.location+'</p>';
};

window.location.onhashchange = function (event) {
    document.getElementById('lastevent').innerHTML = event.type + ' : ' + event.state.url;
};

</script>    
</head>
<body>
    <article>
      <p >HTML5 History API is <b id="status">Not</b> supported</p>
      <script>document.getElementById('status').innerHTML = history.pushState === 'undefined' ? 'NOT' : '';</script>
      <p><em>Last event fired: <span id="lastevent">(none)</span></em></p>
      <p>To test the History API, click through the urls below. Note that none of these urls point to <em>real</em> pages. JavaScript will intercept these clicks, load data and the browser address bar will <em>appear</em> to change - but this is the History API in action!</p>
      <p>Use the back and forward buttons in your browser to navigate the history.</p>
      <ul id="examples">
        <li><a href="/loc.html"       onclick="return linkClick(event, this)">start</a></li>
        <li><a href="/history/first"  onclick="return linkClick(event, this)">first</a></li>
        <li><a href="/history/second" onclick="return linkClick(event, this)">second</a></li>
        <li><a href="/history/third"  onclick="return linkClick(event, this)">third</a></li>
      </ul>
      <p><small>Note: since these urls aren't real, refreshing the page will land on an invalid url.</small></p>
      <div id="output"></div>
    </article>
</body>

</html>

Demo地址: http://haiyang.me/demo/loc.html


>> 留言评论