gpt4 book ai didi

css - 如何检查样式 ID 是否包含某些 css 选择器?

转载 作者:行者123 更新时间:2023-11-28 10:24:05 25 4
gpt4 key购买 nike

我在用于主题选项的 php 文件中有以下代码:

<style type="text/css" id="compiled_styles">
menu {color: red;}
</style>

如何检查ID为“compiled_styles”的样式是否包含某些css选择器?

基本上,如果该样式不包含任何 css 选择器,我需要不显示像这样不必要的空代码:

<style type="text/css" id="compiled_styles">

</style>

最佳答案

首先,我认为您的意思是在某些样式中存在一些 CSS 规则,而不仅仅是选择器。你可以试试这个:

var style = document.querySelector('#compiled_styles');
var ss = style.sheet || style.styleSheet;
var hasSomeRule = (ss.rules || ss.cssRules).length;
//remove the style if it's empty
if(!hasSomeRule) (style.parentNode || style.parentElement).removeChild(style);

Demo 1

另一种解决方案是尝试获取样式元素的一些文本,如果它不为空,它应该有一些特定的规则:

var style = document.querySelector('#compiled_styles');
var hasSomeRule = style.innerHTML.replace(/^\s+$/,'').length;
//remove the style if it's empty
if(!hasSomeRule) (style.parentNode || style.parentElement).removeChild(style);

Demo 2.

关于css - 如何检查样式 ID 是否包含某些 css 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23832647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com