匹配 URL 中的特定值时是否有适用的 CSS 选择器?

问题描述 投票:0回答:5

是否有一个选择器指定 CSS 仅在匹配特定 URL 或 URL 的一部分时应用?

例如,这是我的 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 媒体查询允许您在视图宽度发生变化时切换到不同的样式集。当用户要在屏幕上查看或将其发送到打印机时,它还允许您指定一组不同的样式。

我的问题又是,“是否可以根据 URL 或 URL 中的值指定一组不同的样式。”所以这不是如何做我所要求的事情的问题,而是是否可能做到的问题。

我正在使用 CMS,它有一个允许您添加自己的 CSS 的主题。有一个样式表。就是这样。不是两个,而是一个。

我有一个页面,并且只有该页面具有特定的 CSS。这就是这个问题的由来。可能有一千种解决方法,但我的问题不是关于解决方法。

但是,既然已经回答了这个问题,我不介意与该问题相关的解决方法答案。

css url css-selectors
5个回答
15
投票

看起来

@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

更多信息


3
投票

您可以在 HTML 中或使用 JavaScript 将

data-url
自定义属性附加到元素的祖先,然后在 CSS 中查询该数据的值。这是一个工作示例,其中
data-url
属性位于
body
元素上:

const navigator = document.getElementById('navigator')
const blogUrl = 'https://mywebsite.com/blog';
const aboutUrl = 'https://mywebsite.com/about'

navigator.onclick = () => {
  document.body.dataset.url = document.body.dataset.url === blogUrl ? aboutUrl : blogUrl
};
body::before {
  content: "Current url: " attr(data-url);
}

body[data-url*="blog"] .url-based {
  background-color: red;
}

body[data-url*="blog"] .url-based::after {
  content: "You're on the blog page!"
}

.url-based::after {
  content: "You're not on the blog page."
}

#navigator {
  display: block;
  margin-top: 10px;
}

.box {
  border: 2px solid black;
  padding: 20px;
  margin-top: 5px;
}
<body data-url="https://mywebsite.com/blog">
  <button id="navigator" type="button">Navigate</button>
  <div class="box url-based"></div>
  <div class="box not-url-based">My styling is not based on the current url.</div>
</body>

不知道这样的解决方案的性能如何。


2
投票

遗憾的是,没有伪类可以根据 URL 选择元素。唯一的方法是将类添加到 body 标记或特定元素,然后覆盖 CSS。


1
投票

如果仅适用于 HTML,请使用 jQuery

<script>
        var currentLocation = window.location.pathname;

        if (currentLocation == 'home.html'){
        $('head').append('<link href="home-style.css" rel="stylesheet">');
        } else if (currentLocation == 'about.html'){
        $('head').append('<link href="about-style.css" rel="stylesheet">');
        } else {
        $('head').append('<link href="index-style.css" rel="stylesheet">');
        }
    </script>

如果使用 WordPress:

添加你的主题function.php

  function site_stil_script() {
    
    if ($_SERVER['REQUEST_URI']=='/YOURPAGE/') {
        wp_enqueue_style( 'theme_css', get_template_directory_uri() . '/assets/css/theme-difrent-style.css', array(), '20120208', 'all' );
    } else {
        wp_enqueue_style( 'theme_css', get_template_directory_uri() . '/assets/css/theme-style.css', array(), '20120208', 'all' );
    }
//other lines....
}
add_action( 'wp_enqueue_scripts', 'site_stil_script' );

0
投票

是的!!

对于我的用例,这可以通过 :target css 伪类实现

https://www.w3schools.com/cssref/sel_target.php

<a href="#someid">link to current page (ends up in url after #)</a>
<div id="someid">target of previous link</div>

<style>
    #someid:target {
        background-color: green;
    }
</style>

但是对于您的用例,您需要在您的网址中添加类似以下内容: about.html#about home.html#home

© www.soinside.com 2019 - 2024. All rights reserved.