Is it possible to remove inline styles with jQuery

2019-01-02 14:33发布

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

What's the best (lazy) way?

标签: jquery
13条回答
千与千寻千般痛.
2楼-- · 2019-01-02 14:58

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.

查看更多
爱死公子算了
3楼-- · 2019-01-02 15:07

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

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

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

Worked for me!

查看更多
柔情千种
4楼-- · 2019-01-02 15:07

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

$('#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="">
查看更多
琉璃瓶的回忆
5楼-- · 2019-01-02 15:08

You can set the style using jQuery's css method:

$('something:visible').css('display', 'none');
查看更多
琉璃瓶的回忆
6楼-- · 2019-01-02 15:09
$('div[style*=block]').removeAttr('style');
查看更多
深知你不懂我心
7楼-- · 2019-01-02 15:09

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

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

UPDATE:
I've made an interactive fiddle to 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 value and removeProperty(). They all result in the same fallback – which is either a pre-given CSS rule or the browser's default value.

查看更多
登录 后发表回答