Created
May 5, 2016 15:38
-
-
Save iflamed/94b9990cf95fefa11c9434f57a36a158 to your computer and use it in GitHub Desktop.
SPA单页面应用在切换hash的时候,往往要更改页面标题,一般是通过document.title来设置。 但是iOS 或者微信里面是有坑的,需要hack 一下
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// eg.1 | |
document.title='new title' | |
//eg.2 | |
document.getElementsByTagName('title')[0].innerHTML = 'new title' | |
//这个方式 只能够在android 下面生效 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//基于jQuery或Zepto | |
function change_title(title){ | |
document.title = title; | |
// hack在微信等webview中无法修改document.title的情况 | |
var $iframe = $('<iframe src="/favicon.ico"></iframe>'); | |
$iframe.on('load',function() { | |
setTimeout(function() { | |
$iframe.off('load').remove(); | |
}, 0); | |
}).appendTo($('body')); | |
} | |
$('#demo1').on('click', function(){ | |
change_title('demo1 title'); | |
}); | |
// 原生触发 | |
function changeTitle(title){ | |
var body = document.getElementsByTagName('body')[0]; | |
document.title = title; | |
var iframe = document.createElement("iframe"); | |
iframe.setAttribute("src", "/favicon.ico"); | |
iframe.addEventListener('load', function() { | |
setTimeout(function() { | |
iframe.removeEventListener('load'); | |
document.body.removeChild(iframe); | |
}, 0); | |
}); | |
document.body.appendChild(iframe); | |
} | |
document.getElementById('demo2').ontouchend = function(){ | |
changeTitle('demo2 title'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment