删除 <link>元素与jQuery? [英] Removing <link> element with jQuery?

查看:25
本文介绍了删除 <link>元素与jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't want to use styles from style.css, so I decided to remove style.css from DOM. This work just fine in Firefox and IE8, but not in IE6:

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

任何其他解决方案,使用 jQuery?

Any other solution, with jQuery?

示例如下:
HTML:

Here is example:
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):

And here is CSS (style.css):

#content {
    background-color:#333;
}

仅在 IE 中 #content 仍然是黑暗的.:(
也许是 jQuery 错误?

Only in IE #content is still dark. :(
Maybe is jQuery bug?

推荐答案

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

这个问题似乎是由于 Internet Explorer 在从 DOM 中删除 LINK 元素后没有正确重新呈现页面这一事实引起的.

It seems this problem is being caused by the fact that Internet Explorer does not correctly re-render the page after removing the LINK element from the DOM.

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

In this particular case, the LINK tag is no longer present at the DOM, but IE still displays the CSS that has been loaded into memory.

解决方法/解决方案是使用 .disabled 属性禁用样式表,如下所示:

A workaround / solution for this is to disable the stylesheet using the .disabled property like this:

// 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 将其删除,请使用以下代码:

Or, if you want to remove it by the href use the following code:

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;
    }
}

这篇关于删除 &lt;link&gt;元素与jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆