简体   繁体   中英

How can I remove programmatically-added styles in Chrome?

I have a simple paragraph with two buttons which respectively color it and remove the color. The color removal works in Firefox, but not in Chrome (chromium-browser, to be precise). If I were to add the style through a style attribute ( <p id="paragraph" style="color: #f00;"> ) rather than programmatically ( $('#paragraph').css('color', '#f00'); or document.getElementById('paragraph').style.color="#f00"; ), then the color removal would work on both browsers. Unfortunately, this is impossible in my real-world situation. How else can I make this work?

The code looks like this:

html

<p id="paragraph">TARGET</p>
<input type="button" value="Style me" onclick="styleIt();" />
<input type="button" value="Strip styles" onclick="stripStyles();" />

javascript

function styleIt()
{
    $('#paragraph').css('color', '#f00');
}

function stripStyles()
{
    $('#paragraph').removeAttr("style");
}

jsFiddle : http://jsfiddle.net/qBtYW/10/

PS I'm pretty sure the problem resides in the way removeAttr behaves in different browsers, but I could be wrong.

edit I realise I could use css('color', '') but I'm looking for something that will remove all styles, even those I didn't know were there...

You could just set the style attribute equal to an empty string:

function stripStyles()
{
  $('#paragraph').attr('style', "");
}

I'm not sure why removeAttr is having problems, but I think this should work in all browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM