简体   繁体   中英

Modifying a Matched CSS Rule

Im wondering if it possible to modify a matched CSS rule's height using jquery/javascript.

This is my code so far:

css

.ac-container input:checked ~ article.prorate{
    height: 450px;
}

.prorateTax {
     display: none;
     background: #CEF6CE;
}

jQuery

<script type="text/javascript">
$('.checkTax').change(function () {
    if ($(this).attr("checked")) {
        $('.prorateTax').fadeIn();
        $('.ac-container input:checked ~ article.prorate').css("height", "+=47px");
    } else {
        $('.prorateTax').fadeOut();
        $('.ac-container input:checked ~ article.prorate').css("height", "-=47px");
    }
});
</script>

I have a checkbox you can select which will fade in a hidden div and then increase the height of another div to fit the new section in. I was hoping it would just modify the height of the css match provided in the css. However, instead it sets the element.style of the current div to set height. is it possible to just modify the matched CSS rule?

css() only works over the inline styles:

When using .css() as a setter, jQuery modifies the element's style property.

There are two problems with your code, AFAICS.

  • You must use $(this).prop("checked") instead of attr()
  • In the else branch, you must either use the selector input:not(:checked) or omit the :checked altogether
$('.checkTax').change(function () {
    if ($(this).prop('checked')) {
        $('.prorateTax').fadeIn();
        $('.ac-container input:checked ~ article.prorate').css("height", "+=47px");
    } else {
        $('.prorateTax').fadeOut();
        $('.ac-container input:not(:checked) ~ article.prorate').css("height", "-=47px");
    }
});

JSFiddle

No, you can't overwrite the CSS rule itself as far as I know.
.css() only writes to the the element's style attribute, which has the highest specificity .

An alternative would be to add a second class with a higher specificity, but you'd still kinda be doing the same thing. The main advantage to this approach is that you remove css stuff from javascript, which makes it unobtrusive.

CSS

.ac-container input:checked ~ article.prorate{
    height: 450px;
}

.ac-container input:checked ~ article.prorate.fadein{
    height: 497px; 
}

.prorateTax {
     display: none;
     background: #CEF6CE;
}

JQuery

$('.checkTax').change(function () {
    if ($(this).is(":checked")) {
        $('.prorateTax').fadeIn();
        $('.ac-container input:checked ~ article.prorate').addClass("fadein");
    } else {
        $('.prorateTax').fadeOut();
        $('.ac-container input:checked ~ article.prorate').removeClass("fadein");
    }
});

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