美文网首页
history详解及实例应用

history详解及实例应用

作者: 小疯子的逆时光 | 来源:发表于2016-12-16 10:31 被阅读0次

    DOM中的window对象通过window.history方法提供了对浏览器历史记录的读取,让你可以在用户的访问记录中前进和后退。

    picupload.php:

    //处理上传,获得上传后的img_path地址,省略

    $this->display('picupload.html', array('img_path' => $img_path));

    picupload.html:

    if(window.parent){

    window.parent.addImgSuccess(img_path);

    }

    main.js:

    var org_index = 0;

    //"返回"触发事件,settimeout防止有些浏览器首次加载时触犯popstate

    window.addEventListener('load', function() {

    setTimeout(function() {

    window.addEventListener('popstate', function() {

    $('article').addClass('hid');

    $('[node-type="basic_block"]').removeClass('hid');

    });

    }, 0);

    });

    $('[node-type="pic_a"]').tap(function(){

    $('[node-type="basic_block"]').addClass('hid');

    $('[node-type="upload_block"]').removeClass('hid');

    var state = history.state;

    history.pushState(state, null, window.location+'#upload');

    org_index = history.length;

    });

    $('[node-type="pic_input"]').change(function(){ addPic(); });

    //上传控件执行触发form提交

    addPic : function() {

    $("#pic_form").submit();

    },

    //上传头像成功

    addImgSuccess : function(img_path, data) {

    //兼容不同浏览器,一些浏览器加载window对象时会push新的state,history.length会增加

    var go_index = org_index - history.length - 1;

    history.go(go_index);

    },

    页面原型:

    三,问题分析

    1,iframe实现图片异步上传

    原理:将图片上传的页面放在iframe中,这样就可以在iframe中将图片提交到服务器而不需要页面刷新,提交成功后用脚本实现回到主页面并显示上传的图片。

    2,页面初次加载state对象各浏览器兼容问题

    当页面加载时,它可能会有一个非空的state对象,这可能发生在当页面设置一个state对象(使用pushState或者replaceState)之后用户重启了浏览器。当页面重新加载,页面将收到onload事件,但不会有popstate事件。然而,如果你读取history.state属性,将在popstate事件发生后得到这个state对象,所以在"返回"触发事件,使用settimeout防止有些浏览器首次加载时触犯popstate

    3,window内iframe使用state各浏览器兼容问题

    不同浏览器对iframe中history操作不一样,如Firefox执行history.back/go(-1)是iframe内后退,而Chrome是父页面后退,我们这里是需要实现父页面回退,根据state变化动态获取需要回退的步数:

    var go_index = org_index - history.length - 1;

    history.go(go_index);

    页可以根据不同的浏览器判断,不过需要对浏览器一一了解,不推荐,如下:

    var explorer =navigator.userAgent;

    var str = JSON.stringify(window.location);

    //ie

    if (explorer.indexOf("MSIE") >= 0) {

    history.go(-1);

    }

    //firefox

    else if (explorer.indexOf("Firefox") >= 0) {

    history.go(-2);

    }

    //Chrome

    else if (explorer.indexOf("Chrome") >= 0) {

    }

    //Opera

    else if (explorer.indexOf("Opera") >= 0) {}

    //Safari

    else if (explorer.indexOf("Safari") >= 0) {}

    //Netscape

    else if (explorer.indexOf("Netscape")>= 0) {}

    相关文章

      网友评论

          本文标题:history详解及实例应用

          本文链接:https://www.haomeiwen.com/subject/dzlnmttx.html