Is it possible to create css class at runtime? But with caveat!

0

I have a question that can be of help to many, the question is that in a form html we make much use of style class (css) to make life easier, it happens that being creating classes for some situations gets boring and many Sometimes we repeat the class but with another name for not remembering that we had already created something similar, for example

<style>
.w30px{ width: 30px; }
</style>

We do this because it's so much easier than just putting style into the

<div class="w30px">TEXTO</div>

The natural creation sequence is: we create the style file (css) then set the classes in the objects within the page as needed.

Great, it makes it much easier, but now comes the question:

How can I create the class at runtime according to the name of the class that is in the object? I would like to automate the creation process just by giving the class a name and a function would create the style.

Example onload page:

<script>
  function CriaEstilos(objeto){
    var w = substr($(objeto).prop("class"), 1, 2);
    $(objeto).css("width", w);
  }
</script>

I have not tested the above idea, it is merely illustrative, rsrs

But the idea is to automate the creation of simple classes with a common denominator, in this case the width of the object.

    
asked by anonymous 08.06.2016 / 16:01

1 answer

0

I have a simple solution, but it works until you find a more elegant solution:

$(document).ready(function () {
  
  $(".wpx").before( function() {

    var x = $(this).prop("class"); 
    var n = x.indexOf("lpx") + 3;
    var largura = x.substr(n, 3); // Considerar valor ate 999px
    
    alert("A largura do div sera: "+largura+" px");
    
    $(this).css("border", "solid");
    $(this).css("width", largura);

  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="wpx outraclasse lpx200">CLASSE DINAMICA 1</div>
<div class="wpx lpx300">CLASSE DINAMICA 2</div>
<div class="wpx lpx400">CLASSE DINAMICA 3</div>
<div class="wpx lpx500">CLASSE DINAMICA 4</div>
<p>
  Objetivo:
  <br>Ajustar largura do objeto conforme valor passado na classe lxp
</p>

Variable "lpx" becomes reserved word and no matter where it is positioned according to the div 1

    
08.06.2016 / 18:04