使用 jQuery 删除 元素?

2024-04-29

我不想使用 style.css 中的样式,因此我决定从 DOM 中删除 style.css。这在 Firefox 和 IE8 中工作正常,但在 IE6 中不行:

$("LINK[href='http://www.example.com/style.css']").remove();

还有其他解决方案吗?使用 jQuery?


这是示例:
HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script type="text/javascript" src="path/to/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("link[href*='style.css']").remove();         
});
</script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="content">...</div>
</body>
</html>

这是 CSS (style.css):

#content {
    background-color:#333;
}

仅在 IE 中 #content 仍然是黑色的。 :(
也许是 jQuery 的 bug?


这不是 jQuery 中的错误,而是 IE 渲染引擎的错误(或者可能是一个功能)。

此问题似乎是由于 Internet Explorer 在从 DOM 中删除 LINK 元素后未正确重新呈现页面而引起的。

在这种特殊情况下,LINK 标签不再出现在 DOM 中,但 IE 仍然显示已加载到内存中的 CSS。

解决方法/解决方案是使用以下命令禁用样式表.disabled像这样的属性:

// following code will disable the first stylesheet
// the actual DOM-reference to the element will not be removed; 
// this is particularly useful since this allows you to enable it
// again at a later stage if you'd want to.
document.styleSheets[0].disabled = true;

编辑回复您的评论:

或者,如果您想通过 href 删除它,请使用以下代码:

var styleSheets = document.styleSheets;
var href = 'http://yoursite.com/foo/bar/baz.css';
for (var i = 0; i < styleSheets.length; i++) {
    if (styleSheets[i].href == href) {
        styleSheets[i].disabled = true;
        break;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 jQuery 删除 元素? 的相关文章

随机推荐