是否有选择器指定仅在匹配特定 URL 或 URL 的一部分时才应用 CSS?
例如,这是我的 CSS 样式表:
p {
color: green;
}
url("home.html") {
color: blue;
}
url("about.html") {
color: yellow;
}
path("/path/index*") {
color: indigo;
}
当用户访问 home.html 时,我希望应用 home.html 选择器。当我访问 about.html URL 时,我希望应用 about.html。
CSS 媒体查询允许您在 View 宽度发生变化时切换到一组不同的样式。它还允许您在用户要在屏幕上查看或将其发送到打印机时指定一组不同的样式。
我的问题又是,“是否可以根据 URL 或 URL 中的值指定一组不同的样式。”所以这不是如何做我所要求的问题,而是如果可能的话。
我使用的是 CMS,它的主题允许您添加自己的 CSS。有一个样式表。就是这样。不是两个而是一个。
我有一个页面具有特定于该页面的 CSS,并且只有该页面。这就是这个问题的由来。可能有上千种解决方法,但我的问题不是关于解决方法。
但是,既然已经回答了这个问题,我不介意与该问题相关的变通方法答案。
最佳答案
看起来 @document
规则只是针对这种情况提出的,但它已从 CSS3 规范中删除并计划用于 CSS4。从我的测试来看,它似乎不受支持,也没有列在 caniuse 上。在发帖时。
语法如下:
@document url("http://www.example.com/widgets/") {
body {
color: white;
background: tomato;
}
}
/* The above applies styles only to the page at the given URL */
@document url-prefix("http://www.example.com/widgets/") {
/*
Styles written here are applied to all URLs that
begin with 'http://www.example.com/widgets/'
*/
}
@document regexp("https:.*") {
/* Styles written here are applied to all URLs that begin with 'https:' */
}
使用@media
查询比较的测试代码:
var styleTag = document.createElement ("style");
document.head.appendChild (styleTag);
var sheet = styleTag.sheet;
sheet.insertRule ("@media (min-width:600px) { html {color:red}}", 0);
console.log(document.styleSheets.length);
结果:
// no errors, stylesheet is added
测试代码测试@document
规则:
var styleTag = document.createElement ("style");
document.head.appendChild (styleTag);
var sheet = styleTag.sheet;
sheet.insertRule ("@document url('http://www.google.com') { html {color:red}}", 0);
结果:
/*
Exception: SyntaxError: An invalid or illegal string was specified
@Scratchpad/3:4:0
*/
关于@document 感谢@BoltClock
更多info
关于css - 在匹配 URL 中的特定值时是否有适用的 CSS 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45727055/