我对链接的新标签有疑问。
无论如何,在用户单击链接之前,我是否可以设置浏览器选项卡标题?如果新标签中包含的html不具有title属性,则似乎无法辩论新标签的标题。我对吗?如何设置标题?
//the href is dynamic so I can't set them one by one because I have 100+ html file here
<a href="test.html" target="_blank">open me<a>
有了它,这是不可能的,因为您的链接只是普通的HTML链接。当新页面在新选项卡中打开时,当前页面将没有任何引用,因此无法以任何方式对其进行更改。您将需要使用javascript打开页面并以这种方式设置标题。
您可以动态地设置它window onload
以查找所有a
标签并添加click
事件,从而打开窗口并设置标题。
如果每个页面需要不同的标题,则可以将其存储data-
在a
标记的属性中。
请注意,这仅适用于相同域中的页面(出于安全性考虑),并且不能右键单击并按“在新窗口中打开”来处理用户。但是,Windows中的中键单击似乎确实起作用。
的HTML
<a href="test.html" data-title="A new page" target="_blank">open me</a>
的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]));
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句