Select 只有指向安全站点 (https) 的链接才能更改颜色

Select only links pointing to secure sites (https) to change color

我正在尝试使用 CSS 的不同选择器。我很迷惑。我只想更改指向安全站点 (https) 的链接。我想更改安全链接的颜色。我怎样才能做到这一点? 这里的代码包含前两个 https 和其余的 http:

a {
    color: #333;
    font-size: 20px;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Selectors</title>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="exercise.css" />
  </head>
  <body>
    <a href="https://www.google.com">Google</a>
    <a href="https://www.google.com">Google</a>
    <a href="http://www.google.com">Google</a>
  </body>
</html>

使用[href^="https://"]。选择 href 以 https://.

开头的所有 a 标签

a {
    color: #333;
    font-size: 20px;
}
a[href^="https://"] {
  color: red;
} 
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Selectors</title>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="exercise.css" />
  </head>
  <body>
    <a href="https://www.google.com">Google</a>
    <a href="https://www.google.com">Google</a>
    <a href="http://www.google.com">Google</a>
  </body>
</html>

有关属性选择器的更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors

不幸的是,某些 http 链接具有端口 443,这也强制使用 HTTPS。无法使用 CSS 设置此类链接的样式,但使用 JavaScript:

可能会有一些希望

// Get all links with href attribute
const links = document.querySelectorAll('a[href]');

for (var i = 0; i < links.length; i++) {
  const link = links[i];
  const href = link.href;
  const split = href.replace("http://", "");
  const parts = split.split("/");
  if (parts[0].endsWith(":443")) {
    link.classList.add('red');
  }
}
a {
    color: #333;
    font-size: 20px;
}
a[href^="https://"] {
  color: red;
}
.red {
  color: red;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Selectors</title>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="exercise.css" />
  </head>
  <body>
    <a href="https://www.google.com">Google</a>
    <a href="https://www.google.com">Google</a>
    <a href="http://www.google.com">Google</a>
    <a href="http://www.google.com:443">Google</a>
  </body>
</html>