Remove a specific inline style with Javascript|jQuery

前端 未结 7 2115
走了就别回头了
走了就别回头了 2020-12-08 01:46

I have the following code in my html:

hello world

相关标签:
7条回答
  • 2020-12-08 02:07

    From what I can see you really need two different styles for the paragraph. It might be easier to set those up in CSS and then just use jQuery to remove / add as you need:

    #styleOne { color: red; font: normal 14pt Verdana; text-align: center; }
    
    #styleTwo{ color: #000; font: normal 11pt Arial; text-align: center; }
    

    Your initial html will look like:

    <p id="styleOne">hello world</p>
    

    And then to revert to styleTwo in jQuery

    $('p#styleOne').removeClass('styleOne').addClass('styleTwo');
    
    0 讨论(0)
  • 2020-12-08 02:08

    My suggestion would be to stay away from setting this stuff using inline styles. I would suggest using classes and then using jQuery to switch between them:

    CSS:

    #foo{ font-size:11pt; font-family:arial; color:#000; }
    #foo.highlight {text-align:center; font-size:14pt; font-family:verdana; color:red}
    

    HTML:

    <p id="foo" class="highlight">hello world</p>
    

    Javascript:

    $('#foo').removeClass('highlight');
    $('#foo').addClass('highlight');
    
    0 讨论(0)
  • 2020-12-08 02:10

    I think there is no proper solution to this problem (without changing your markup). You could search and replace the style attribute's value:

    var element = $('#foo');
    element.attr('style', element.attr('style').replace(/font-size:[^;]+/g, '').replace(/font-family:[^;]+/g, ''))
    

    By far the best solution would be to get rid of the inline styles and manage the styles by using classes.

    0 讨论(0)
  • 2020-12-08 02:21

    For those that aren't using jQuery, you can delete specific styles from the inline styles using the native removeProperty method. Example:

    elem.style.removeProperty('font-family');
    

    Of course, IE < 9 doesn't support this so you'll have to use

    elem.style.removeAttribute('font-family');
    

    so a cross browser way to do it would be:

    if (elem.style.removeProperty) {
        elem.style.removeProperty('font-family');
    } else {
        elem.style.removeAttribute('font-family');
    }
    
    0 讨论(0)
  • 2020-12-08 02:21

    Set the properties to inherit:

    $('#foo').css('font-family','inherit').css('font-size','inherit');
    
    0 讨论(0)
  • 2020-12-08 02:25

    dynamic add and remove inline style property

    var check=()=>{
    console.log('test')
    var el=document.getElementById("id");
    
    var condition=el.style['color']!=""?true:false;
    
    if(condition){
    
    el.style.removeProperty('color')
    
    }
    else{
    
    el.style.color="red"
    
    }
    
    
    }
    <div id="id" style="display:block">dynamic style</div>
    
    
    <button onclick="check()">apply style</button>

    0 讨论(0)
提交回复
热议问题