简体   繁体   中英

How do I get a CSS property value from a style tag?

I have the following code in the of the page (along with other tags) and I want eventually to retrieve the numeric value of "z-index" into a variable:

<style>
.main_style {
  font-family:Verdana, Arial, Helvetica, sans-serif;
  font-size:11px;
  color:#CCC;
  text-align:center;
  border:7px solid #333;
  -moz-border-radius:5px /;
  border-radius:5px / 5px;
  background-color:#333;
  z-index:1000;
  width:auto;
  min-width:0;
  max-width:1000px;
  height:auto;
  min-height:0;
  max-height:1000px;
  margin:0;
}
</style>

I thought of the following (with jQuery and Javascript) but I am sure it is not the most efficient way to do this:

var a1=$("style:contains('.main_style')").html();
var a2=+a1.match(/z-index: (\d*?);/i)[1];

Here is its FIDDLE: http://jsfiddle.net/R2S4q/

Any other ideas on what is the best approach?

I hope this should help you

<style>
    p {z-index: 99}
</style>

$(document).ready(function() {
    var $p = $("<p></p>").hide().appendTo("body");
    alert($p.css("z-index"));
    $p.remove();
});

You can even get CSS property without adding element to the DOM

$('<p/>').css('z-index')
  • document.styleSheets holds an object of all stylesheets in the document.
  • each stylesheet object has a cssRules property: A read-only, array-like object holding the CSSRule objects that compose the stylesheet
  • each CSSRule object has a cssText property that is the value of that css rule.

...yeah, better use jQuery...

If you are unable to use a selector like other's have mentioned (eg - $('.main_style').css('z-index'); ), you can use document.styleSheets

This will return an array of CSSStyleSheet objects that you can iterate through. Not sure if this is more efficient and the code is certainly more complex. You may be better off with your solution but here's a fiddle if you want to check it out.

http://jsfiddle.net/fehays/WWxru/1/

var rules = [];
for (var i = 0; i < document.styleSheets.length; i++) {
    var sheet = document.styleSheets[i];
    if (sheet.ownerNode.nodeName == 'STYLE') {
        rules.push(sheet.rules);
    }
}
for (var i = 0; i < rules.length; i++) {
    var rule = rules[i];
    for (var j = 0; j < rule.length; j++) {
        if (rule[j].selectorText == '.main_style') {
            $('#test').html(rule[j].style.zIndex);
        }
    }
}

A simple jquery solution like this would work as well:

$('<span />').addClass('main_style')
    .css('position','relative')
    .hide()
    .appendTo('body');

$('#test').html($('.main_style').css('z-index'));

你可以使用jQuery .css()函数吗?

var z_index = $('.your_class').css('z-index')

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