javascript动态修改浏览器标题(title)方法

PHPz
Release: 2018-09-28 14:39:01
Original
4093 people have browsed it

给大家讲一个用javascript动态修改浏览器标题(title)方法和技巧,需要的朋友把代码测试吧。

title在html中属于特殊的节点元素.因为它可以使用document.getElementsByTagName("title")[0]来获取网页的title标签,但却无法用document.getElementsByTagName("title")[0].innerHtml用更改它的值。经测试原生js有两种方式可以修改,jQuery中也能简单设置。不清楚的小伙伴们可以了解一下。

innerText 方式

通过console.log(document.getElementsByTagName("title")[0]),发现能打印出标签,标签里面只有文字节点,故猜测只能识别TextNode,所以用innerText方式设置title的值,果然成功了。</p>

document.getElementsByTagName("title")[0].innerText = '需要设置的值';
Copy after login

document.title方式

经过测试,还可通过document.title 设置title的值。

console.log(document.title); # 可以获取title的值。 document.title = '需要设置的值'; # 设置title的值。
Copy after login

例子:

window.onfocus = function () { document.title = '恢复正常了...'; }; window.onblur = function () { document.title = '快回来~页面崩溃了'; };
Copy after login

我们在浏览器取得了焦点和失去焦点的时候改变title的值,可以发现切换浏览器选项卡的时候,title发生了改变。

jQuery方式

当然如果你的项目里面依赖jQuery,可以使用jq的方法设置

$('title').html('') $('title').text('')
Copy after login

jq中两种方式都可以实现

总结

原生js中我们可以通过 innerText , document.title 两种方式动态修改网页的title .

jq中我们可以通过 $('title').html('') 或者 $('title').text('') 进行修改。

以上就是javascript动态修改浏览器标题(title) 的详细方法,更多相关教程请访问JavaScript视频教程

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!