是否可以使用 jQuery 删除内联样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2465158/
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-26 13:34:20  来源:igfitidea点击:

Is it possible to remove inline styles with jQuery?

jquery

提问by Haroldo

A jQuery plugin is applying an inline style (display:block). I'm feeling lazy and want to override it with display:none.

一个 jQuery 插件正在应用内联样式 ( display:block)。我感觉很懒惰,想用display:none.

What's the best (lazy) way?

最好的(懒惰的)方法是什么?

回答by Joseph Silber

Update:while the following solution works, there's a much easier method. See below.

更新:虽然以下解决方案有效,但有一个更简单的方法。见下文。



Here's what I came up with, and I hope this comes in handy - to you or anybody else:

这是我想出的,我希望这能派上用场 - 对您或其他任何人:

$('#element').attr('style', function(i, style)
{
    return style && style.replace(/display[^;]+;?/g, '');
});

This will remove that inline style.

这将删除该内联样式。

I'm not sure this is what you wanted. You wanted to override it, which, as pointed out already, is easily done by $('#element').css('display', 'inline').

我不确定这是你想要的。您想覆盖它,正如已经指出的那样,可以通过$('#element').css('display', 'inline').

What I was looking for was a solution to REMOVE the inline style completely. I need this for a plugin I'm writing where I have to temporarily set some inline CSS values, but want to later remove them; I want the stylesheet to take back control. I could do it by storing all of its original values and then putting them back inline, but this solution feels much cleaner to me.

我正在寻找的是完全删除内联样式的解决方案。我需要这个插件来编写我必须临时设置一些内联 CSS 值的插件,但以后想删除它们;我希望样式表收回控制权。我可以通过存储它的所有原始值然后将它们放回内联来做到这一点,但这个解决方案对我来说感觉更清晰。



Here it is in plugin format:

这是插件格式:

(function($)
{
    $.fn.removeStyle = function(style)
    {
        var search = new RegExp(style + '[^;]+;?', 'g');

        return this.each(function()
        {
            $(this).attr('style', function(i, style)
            {
                return style && style.replace(search, '');
            });
        });
    };
}(jQuery));

If you include this plugin in the page before your script, you can then just call

如果您在脚本之前的页面中包含此插件,则可以调用

$('#element').removeStyle('display');

and that should do the trick.

这应该可以解决问题。



Update: I now realized that all this is futile. You can simply set it to blank:

更新:我现在意识到这一切都是徒劳的。您可以简单地将其设置为空白:

$('#element').css('display', '');

and it'll automatically be removed for you.

它会自动为您删除。

Here's a quote from the docs:

这是文档中的引用:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '')— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css()method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style>element.

将样式属性的值设置为空字符串 — 例如$('#mydiv').css('color', '')— 如果该属性已被直接应用,则从元素中删除该属性,无论是在 HTML 样式属性中,通过 jQuery 的.css()方法,还是通过样式属性的直接 DOM 操作。但是,它不会删除已在样式表或<style>元素中应用 CSS 规则的样式。

I don't think jQuery is doing any magic here; it seems the styleobject does this natively.

我不认为 jQuery 在这里有什么魔力;似乎style对象本身就是这样做的

回答by heisenberg

.removeAttr("style")to just get rid of the whole style tag...

.removeAttr("style")只是摆脱整个风格标签......

.attr("style")to test the value and see if an inline style exists...

.attr("style")测试该值并查看是否存在内联样式...

.attr("style",newValue)to set it to something else

.attr("style",newValue)将其设置为其他内容

回答by Rick van 't Wout Hofland

The easiest way to remove inline styles (generated by jQuery) would be:

删除内联样式(由 jQuery 生成)的最简单方法是:

$(this).attr("style", "");

The inline code should disappear and your object should adapt the style predefined in your CSS files.

内联代码应该消失,您的对象应该适应您的 CSS 文件中预定义的样式。

Worked for me!

为我工作!

回答by SLaks

You can set the style using jQuery's cssmethod:

您可以使用 jQuery 的css方法设置样式:

$('something:visible').css('display', 'none');

回答by Yukulélé

you can create a jquery plugin like this :

你可以像这样创建一个 jquery 插件:

jQuery.fn.removeInlineCss = (function(){
    var rootStyle = document.documentElement.style;
    var remover = 
        rootStyle.removeProperty    // modern browser
        || rootStyle.removeAttribute   // old browser (ie 6-8)
    return function removeInlineCss(properties){
        if(properties == null)
            return this.removeAttr('style');
        proporties = properties.split(/\s+/);
        return this.each(function(){
            for(var i = 0 ; i < proporties.length ; i++)
                remover.call(this.style, proporties[i]);
        });
    };
})();

usage

用法

$(".foo").removeInlineCss(); //remove all inline styles
$(".foo").removeInlineCss("display"); //remove one inline style
$(".foo").removeInlineCss("color font-size font-weight"); //remove several inline styles

回答by Joel

The Lazy way (which will cause future designers to curse your name and murder you in your sleep):

懒惰的方式(这将导致未来的设计师诅咒你的名字并在你睡梦中谋杀你):

#myelement 
{
    display: none !important;
}

Disclaimer:I do not advocate this approach, but it certainly is the lazy way.

免责声明:我不提倡这种方法,但它肯定是一种懒惰的方法。

回答by David Morton

$("[style*=block]").hide();

回答by antpaw

$('div[style*=block]').removeAttr('style');

回答by WoodrowShigeru

If you want to removea property within a style attribute – not just set it to something else – you make use of the removeProperty()method:

如果您想删除样式属性中的属性——而不仅仅是将其设置为其他内容——您可以使用以下removeProperty()方法:

document.getElementById('element').style.removeProperty('display');


UPDATE:
I've made an interactive fiddleto play around with the different methods and their results. Apparently, there isn't much of a difference between set to empty string, set to faux valueand removeProperty(). They all result in the same fallback – which is either a pre-given CSS rule or the browser's default value.

更新:
我制作了一个交互式小提琴来尝试不同的方法及其结果。显然,set to empty string,set to faux value和之间没有太大区别removeProperty()。它们都会导致相同的回退——要么是预先给定的 CSS 规则,要么是浏览器的默认值。

回答by paulalexandru

In case the display is the only parameter from your style, you can run this command in order to remove all style:

如果 display 是您样式中的唯一参数,您可以运行此命令以删除所有样式:

$('#element').attr('style','');

Means that if your element looked like this before:

意味着如果您的元素以前是这样的:

<input id="element" style="display: block;">

Now your element will look like this:

现在您的元素将如下所示:

<input id="element" style="">