通过id或属性找到<style>标签

3
我希望能够动态地移除或禁用一个如下所示的 <style> 标签。
<style type="text/css" id="cssx/portal/simple-sidebar.css" designtr="cssx/portal/simple-sidebar.css">


#wrapper {
    padding-left: 0;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

#wrapper.toggled {
    padding-left: 250px;
}

#sidebar-wrapper {
    z-index: 1000;
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    overflow-y: auto;
    background: #000;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

</style>

如果我有ID或自己定义的designtr属性,似乎无法像这样禁用或删除它:

        var id = 'x';
        var designtr = 'x';

        document.getElementById(id).disabled = true;  //doesn't work, throws an error saying element is null
        $('style[designtr="' + designtr + '"]').remove();   //doesn't work, although strangely no error thrown

我曾经在某个地方读到过,即使使用HTML5,样式标签也不能具有有效的id属性。

我想做的就是根据手头上的某个唯一id,删除或禁用一个样式标签。


1
那个脚本在页面的哪里?它看起来应该可以工作,但如果脚本在文档中样式标签之前,它将不会被浏览器处理,因此您无法访问它。如果您不想移动脚本,可以将其包装在 $(document).ready(function(){ your code }); 中。 - JackW
你试过使用更传统id 吗? - Joaquín O
嗯,我希望斜杠不会有影响,但我也会测试这个理论,谢谢。 - Alexander Mills
2个回答

4

效果非常好:

document.getElementById('remove').onclick = function () {
  document.getElementById('styl').remove();
};
<div>Some Div Content</div>
<button id="remove">remove</button>
<style id="styl">div{background-color: red}</style>


我的样式标签在body中,如果有任何区别请告诉我。 - Alexander Mills
这个例子中的样式元素也在主体内。 - Amit
是的,我看到你的代码可以运行了,已经点赞了。但是我的代码无法运行,不确定出了什么问题。 - Alexander Mills
然后您应该创建一个 MCVE。 - Amit

1

$(function() {
  $("[id$=css]").remove()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style type="text/css" id="cssx/portal/simple-sidebar.css" designtr="cssx/portal/simple-sidebar.css">


#wrapper {
    padding-left: 0;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

#wrapper.toggled {
    padding-left: 250px;
}

#sidebar-wrapper {
    color:blue;
    z-index: 1000;
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    overflow-y: auto;
    background: #000;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

</style>
<div id="side-wrapper">abc</div>


@AlexMills 请参见http://superuser.com/questions/447269/is-there-any-way-to-view-a-webpage-without-styles-in-chrome - guest271314

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接