使用 JavaScript/jQuery 删除或替换样式表(<link>)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3182840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:35:33  来源:igfitidea点击:

Removing or replacing a stylesheet (a <link>) with JavaScript/jQuery

javascriptjquerycss

提问by Alex

How can I do this?

我怎样才能做到这一点?

I tried

我试过

$('link[title="mystyle"]').remove();

and although the element is removed, the styles are still applied to the current page (in both Opera and Firefox).

尽管该元素已被移除,但样式仍会应用于当前页面(在 Opera 和 Firefox 中)。

Is there any other way?

有没有其他办法?

回答by redsquare

To cater for ie you have to set the stylesheet to be disabled as it keeps the css styles in memory so removing the element will not work, it can also cause it to crash in some instances if I remember correctly.

为了满足 ie 的需要,您必须将样式表设置为禁用,因为它会将 css 样式保留在内存中,因此删除元素将不起作用,如果我没记错的话,它还可能导致它在某些情况下崩溃。

This also works for cross browser.

这也适用于跨浏览器。

e.g

例如

document.styleSheets[0].disabled = true;

//so in your case using jquery try

//所以在你的情况下使用jquery试试

$('link[title=mystyle]')[0].disabled=true;

回答by Alex

I managed to do it with:

我设法做到了:

$('link[title="mystyle"]').attr('disabled', 'disabled');

it seems this is the only way to remove the styles from memory. then I added:

似乎这是从内存中删除样式的唯一方法。然后我补充说:

$('link[title="mystyle"]').remove();

to remove the element too.

也删除元素。

回答by Rory O'Kane

To disable your selected stylesheet:

要禁用您选择的样式表:

$('link[title="mystyle"]').prop('disabled', true);

If you never want that stylesheet to be applied again, you can then .remove()it. But don't do that if you want to be able to re-enable it later.

如果您不想再次应用该样式表,则.remove()可以。但是,如果您想稍后重新启用它,请不要这样做。

To re-enable the stylesheet, do this (as long as you didn't removethe stylesheet's element):

要重新启用样式表,请执行以下操作(只要您没有remove使用样式表的元素):

$('link[title="mystyle"]').prop('disabled', false);

In the code above, it is important to use .prop, not .attr. If you use .attr, the code will work in some browsers, but not Firefox. This is because, according to MDN, disabledis a property of the HTMLLinkElementDOM object, but notan attribute of the linkHTML element. Using disabledas an HTML attribute is nonstandard.

在上面的代码中,重要的是使用.prop,而不是.attr。如果您使用.attr,该代码将在某些浏览器中工作,但不适用于 Firefox。这是因为,根据MDNdisabled所述的属性HTMLLinkElementDOM对象,但不是所述的一个属性link的HTML元素。使用disabled作为HTML属性是非标准的。

回答by Petr Hurtak

no jQuery solution

没有 jQuery 解决方案

if you can add id to your link tag

如果您可以将 id 添加到您的链接标签

<link rel="stylesheet" href="css/animations.css" id="styles-animations">

document.getElementById("styles-animations").disabled = true;

if you know index position of your css file in document

如果您知道 css 文件在文档中的索引位置

document.styleSheets[0].disabled = true; // first
document.styleSheets[document.styleSheets.length - 1].disabled = true; // last

if you want to disable style by name you can use this function

如果要按名称禁用样式,可以使用此功能

/**
 * @param [string]  [styleName] [filename with suffix e.g. "style.css"]
 * @param [boolean] [disabled]  [true disables style]
 */
var disableStyle = function(styleName, disabled) {
    var styles = document.styleSheets;
    var href = "";
    for (var i = 0; i < styles.length; i++) {
        href = styles[i].href.split("/");
        href = href[href.length - 1];

        if (href === styleName) {
            styles[i].disabled = disabled;
            break;
        }
    }
};

note: make sure style file name is unique so you don't have "dir1/style.css" and "dir2/style.css". In that case it would disable only first style.

注意:确保样式文件名是唯一的,这样您就没有“dir1/style.css”和“dir2/style.css”。在这种情况下,它只会禁用第一种样式。

回答by Hasan Al-Natour

To remove a stylesheet:

删除样式表:

$('link[src="<path>"]').remove();

To Replace a stylesheet:

替换样式表:

$('link[src="<path>"]').attr('src','<NEW_FILE_PATH>');

回答by Sky Yip

Using pure javascript:

使用纯 javascript:

var stylesheet = document.getElementById('stylesheetID');
stylesheet.parentNode.removeChild(stylesheet);

回答by fernanDOTdo

ES6 solution:

ES6解决方案:

const disableStyle = styleName => {
  const styles = document.styleSheets;
  let href = "";
  for (let i = 0; i < styles.length; i++) {
    if (!styles[i].href) {
      continue;
    }
    href = styles[i].href.split("/");
    href = href[href.length - 1];
    if (href === styleName) {
      styles[i].disabled = true;
      break;
    }
  }
};

Use it like disableStyle("MyUnwantedFile.css");.

disableStyle("MyUnwantedFile.css");.

回答by NicolasZ

If you want to do it only with the href attribute:

如果您只想使用 href 属性执行此操作:

$('link[href="https://example.com/mycss.css"]').remove()

回答by BuvinJ

Here's both an add & remove using the disabling principle mentioned in a number of these other posts to prevent cross browser issues. Note how my add checks to see if the sheet already exists, in which case it just enables it. Also, in contrast to some answers, this is designed to work using the url to a .css file as the sole argument to the functions (insulating the client from the use of idor titleattributes).

这是使用许多其他帖子中提到的禁用原则进行添加和删除,以防止跨浏览器问题。请注意我的 add 如何检查工作表是否已经存在,在这种情况下它只是启用它。此外,与某些答案相反,这旨在使用 .css 文件的 url 作为函数的唯一参数(将客户端与idtitle属性的使用隔离)。

function element( id ){ return document.getElementById( id ); }

function addStyleSheet( url ){
    var id = _styleSheetUrlToId( url );
    if( !_enableStyleSheet( id ) ) {
        var link  = document.createElement("link");
        link.href = url;
        link.type = "text/css";
        link.rel  = "stylesheet"; 
        link.id   = id; 
        document.getElementsByTagName("head")[0].appendChild( link );
    }
}

function removeStyleSheet( url )
{ _enableStyleSheet( _styleSheetUrlToId( url ), false ); }

// "protected" function
function _styleSheetUrlToId( url ){ 
    var urlParts = url.split("/");
    return urlParts[urlParts.length-1].split(".")[0]
           + "-style";
}

// "protected" function
// returns if the sheet was found 
function _enableStyleSheet( id, enable ) {
    if( typeof(enable) == "undefined" ) enable = true;
    var sheet = element( id );
    if( sheet ) {
        sheet.disabled = !enable;
        return true;        
    }
    return false;
}