apply CSS style to particular elements dynamically

前端 未结 5 2045
我在风中等你
我在风中等你 2021-01-15 19:56

I have a div with paragraphs inside:

...

...

I want dynamically to apply

相关标签:
5条回答
  • 2021-01-15 20:37

    Without using classes:

    /* using CSS */
    div p {
        color: #ff0000;
    }
    
    // using jQuery
    $("div p").css({
        color : "#ff0000"
    });
    

    With classes for <p> elements:

    <!-- HTML -->
    <div>
        <p class="mypar">...</p>
        <p class="mypar">...</p>
    </div>
    
    /* using CSS */
    div p.mypar {
        color: #ff0000;
    }
    
    // using jQuery
    $("div p.mypar").css({
        color : "#ff0000"
    });
    

    With classes for <div> element:

    <!-- HTML -->
    <div class="mydiv">
        <p>...</p>
        <p>...</p>
    </div>
    
    /* using CSS */
    div.mydiv p {
        color: #ff0000;
    }
    
    // using jQuery
    $("div.mydiv p").css({
        color : "#ff0000"
    });
    
    0 讨论(0)
  • 2021-01-15 20:41

    You can apply the CSS dynamically for this example of yours in this way:

    function applyCSS()
    {
        $("div > p").css({
            "background": "#fff",
            "color": "#000"
        });
    }
    

    Or, when you wanna apply this when the page loads:

    $(document).ready(function(){
        applyCSS();
    });
    
    0 讨论(0)
  • 2021-01-15 20:47

    Changing the css dynamically would be as simple as changing the top level class name for example

    <div id="toggleme" class="class1">
      <p>...</p>
      <p>...</p>
    </div>
    <a id="test">Test</a>
    

    .class1 {
     background-color:#F00;
    }
    
    .class1 p {
        color:#00F;
    }
    
    .class2 {
        background-color:#00F;
    }
    
    .class2 p {
     color:#F00;
    }​
    

    then the jquery would be

    $(document).ready(function() {
        $('#test').click(function() {
            $('#toggleme').toggleClass('class1');
            $('#toggleme').toggleClass('class2');
        });
    });​
    

    Everything below the class will change to its new style :)

    fiddle

    0 讨论(0)
  • 2021-01-15 20:48

    With CSS you can define a child selector.

    Building on that, you can dynamically add/remove a style class to your div and the style will apply to the children you specify in that selector.

    Let's assume you want to apply this to a specific div, not any/every one. So give the target div an identifier:

    <div id='foo'>
      <p>...</p>
      <p>...</p>
    </div>
    

    Adding a dynamic style with simple javascript:

    document.getElementById('foo').style.className='dynamic_style'
    

    The CSS (using combined id and class on a child selector):

    div#foo.dynamic_style > p { /* your style definition*/ }
    
    0 讨论(0)
  • 2021-01-15 20:49

    Using CSS:

    div p {your style goes here}
    

    jquery:

    $('div p').css('property', 'value');
    
    0 讨论(0)
提交回复
热议问题