我对链接的新标签有疑问.
无论如何,我可以在用户单击链接之前设置浏览器选项卡标题吗?如果新标签中包含的html不具有title属性,则似乎无法辩论新标签的标题.我对吗?如何设置标题?
//the href is dynamic so I can't set them one by one because I have 100+ html file here
解决方法:
有了它,这是不可能的,因为您的链接只是普通的HTML链接.当新页面在新选项卡中打开时,当前页面将没有任何引用,因此无法以任何方式对其进行更改.您将需要使用javascript打开页面并以这种方式设置标题.
您可以在窗口加载时动态设置此设置,以查找所有标签并添加click事件,从而打开窗口并设置标题.
如果每个页面需要不同的标题,则可以将其存储在标签的data-attribute中.
请注意,这仅适用于同一域中的页面(出于安全性考虑),并且不能右键单击并按“在新窗口中打开”来处理用户. Windows中的中键似乎确实起作用.
HTML
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