//First get the pathname from current window location
const path = window.location.pathname;
//Now we can check whether our current location meet the path we wanted to check
if (path.includes('page-name-1')) {
loadCSSFile('css/page1.css');
} else if (path.includes('page-name-2')) {
loadCSSFile('css/page2.css');
} else {
loadCSSFile('css/page3.css');
}
//This function will create a link tag in our site and load the file. This function take href as a parameter
function loadCSSFile(href) {
const linkElement = document.createElement('link');
linkElement.rel = 'stylesheet';
linkElement.href = href;
document.head.appendChild(linkElement);
}
2条答案
按热度按时间uemypmqf1#
创建一个新的
link
标记,并根据URL的内容给予适当的属性,怎么样?就像这样:zujrkrfu2#
通过检查当前窗口位置,我们可以解决这个问题。我们只需要检查路径名并加载css文件。