js html设置标题,javascript-如何为新的浏览器标签设置标题?

我对链接的新标签有疑问.

无论如何,我可以在用户单击链接之前设置浏览器选项卡标题吗?如果新标签中包含的html不具有title属性,则似乎无法辩论新标签的标题.我对吗?如何设置标题?

//the href is dynamic so I can't set them one by one because I have 100+ html file here

open me

解决方法:

有了它,这是不可能的,因为您的链接只是普通的HTML链接.当新页面在新选项卡中打开时,当前页面将没有任何引用,因此无法以任何方式对其进行更改.您将需要使用javascript打开页面并以这种方式设置标题.

您可以在窗口加载时动态设置此设置,以查找所有标签并添加click事件,从而打开窗口并设置标题.

如果每个页面需要不同的标题,则可以将其存储在标签的data-attribute中.

请注意,这仅适用于同一域中的页面(出于安全性考虑),并且不能右键单击并按“在新窗口中打开”来处理用户. Windows中的中键似乎确实起作用.

HTML

open me

JavaScript的

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

// does the actual opening

function openWindow(event) {

event = event || window.event;

// find the url and title to set

var href = this.getAttribute("href");

var newTitle = this.getAttribute("data-title");

// or if you work the title out some other way...

// var newTitle = "Some constant string";

// open the window

var newWin = window.open(href, "_blank");

// add a load listener to the window so that the title gets changed on page load

newWin.addEventListener("load", function() {

newWin.document.title = newTitle;

});

// stop the default `a` link or you will get 2 new windows!

event.returnValue = false;

}

// find all a tags opening in a new window

var links = document.querySelectorAll("a[target=_blank][data-title]");

// or this if you don't want to store custom titles with each link

//var links = document.querySelectorAll("a[target=_blank]");

// add a click event for each so we can do our own thing

for(var i = 0; i < links.length; i++) {

links[i].addEventListener("click", openWindow.bind(links[i]));

}

});

标签:html,javascript,css

来源: https://codeday.me/bug/20191010/1887622.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值