How to read CSS property of Psuedo class in javasc

2019-09-09 12:17发布

问题:

I've searched SO and googled for this and there are many answers on how to read CSS propeties but non that allow the reading of a pseudo class property.

I have used the following to allow me to easily reuse certain pages (firmware/config upload) on a number of products.

.productname:before
{
    content: "My Shiny New Product";
}

then

<span class="productname" />

in the html to insert the correct name.

Currently when sending a Firmware update to the Server no check is done on the client browser and the server returns [please reboot to contunue...] or [this is not a [productname] update file]. As you can imagine the firmware updates can be quite large and if transfered over 3G take some time.

I want to get the productname from the CSS :before pseudo class to allow me to check the upload file name before send it. I have implemented this JS Fiddle to illustrate the issue.

I have tried putting the content property on the .productname class directly (as a copy placeholder) and FF, Opera and Safari will read this but you guessed it IE returns undefined.

I know I can use a global var in JS and might have to do that but I'd rather have it defined in one place to avoid potential mistakes.

So does anyone know how to (or workaround ) read properies of the :pseudo CSS classes?

Thanks in advance.

Update

Since i cant get a solution for IE8, I've changed to using the following code instead.

window.addEvent( "domready",
function()
{
  window.productName = "My Shiny New Product";      

  var def = '.productname:before { content: "'+window.productName+'"; }';

  var style = new Element("style");
  style.setAttribute( "type", "text/css" );
  if( style.styleSheet )
  {
     style.styleSheet.cssText = def;
  }
  else
  {
    style.innerHTML = def;
  }
  document.getElementsByTagName("head")[0].appendChild(style);
  document.getElementsByTagName("head")[0].appendChild(style);
} );

with reference to this site Dynamic SCRIPT and STYLE elements in IE

回答1:

you can use window.getComputedStyle. however, an answer notes that some browsers may not support this, so tread lightly. here's a demo

<span class="test" />
<span class="test" />
<span class="test" />

.test:before{
    content: "My Shiny New Product";
}

$(function() {

    //get all element class test
    var test = $('.test');

    //each of them, alert the content
    test.each(function() {
        var style = window.getComputedStyle(this, "before");
        alert(style.content);
    });
});​