css dynamic change via jQuery Is it possible?

Asked

Viewed 227 times

1

I have the following structure:

var prop = new Array();
prop[0] = "margin : auto";
prop[1] = "padding : 5px";
prop[2] = "border : none";
...

$(elemento).css({

 for(i=0; i< prop; i++) {
        /*Aqui vão serem feitos os laços do for e vão imprimir a toda linha, alguma coisa como:
       document.write(prop[i]);
        */
        margim: auto,
        /*para cada laço do for, uma linha dessa será criada*/
   }

});

For each element, the print inside the for will be different.

The idea is to see if in the end

The interpreter css, for this case, interprets something as:

$(elemento).css({

        margim: auto,
        padding: 5px;
        border: none,
        etc...    

});

There’s a way to make it work?

On the advice of a colleague here, I came to this solution.

But because it’s json, And inside the variable there are keys, I didn’t know how to solve:

var variavel = 
{ 
  '0%' : { 'margin-left':'-0%'},
 '33%' : { 'margin-left':'-0%'},
 '38%' : { 'margin-left':'-100%'},
 '66%' :{ 'margin-left':'-100%'},
 '71%' : { 'margin-left':'-200%'},
 100%' : { 'margin-left':'-200%'},
}

Here’s the shape I’m using to get to the array:

  var tempoTransicao = 5;
  var quantasImagens = 4;
  var tamanhoIntervalos = Math.round(100/quantasImagens);
  var tempoImagens = 0;
  var t = 0;    
  var imagem = [];


    for (i = 0; i < quantasImagens; i++) {  

        tMin = t + tempoTransicao;
        tMax = t + tamanhoIntervalos;   
        t+=tamanhoIntervalos;

        if(i==0) tMin=0;
        if(i==quantasImagens) tMax=100;       

        imagem[i] = [];
        imagem[i].push(tMin + "% { margin-left:-" + tempoImagens + "%};");
        imagem[i].push(tMax + "% { margin-left:-" + tempoImagens + "%};");

        tempoImagens+=100;

    }

  });

  texto = "";

  for (po=0; po<imagem.length; po++) {
      texto += imagem[po][0]+imagem[po][1];
  }
  • Please read again with more attention to the question. I think you did not understand well. There I did not find what I was looking for. If you know how to do, please post your answer which may serve to others with the same doubt.

  • Does this structure already exist or are you still defining? If you’re still defining, you can use a json for multiple css rules.

  • Thank you for answering. I’m still defining. Could you help me by posting an answer and showing me how you do it. Please? I would be grateful.

  • Brother, by your example, it seems that you want to transition the image from one side to the other, correct?

  • Yes Eduardo. But you can’t tell how many images will be inserted into html. In this case, I need to create the keyframe settings before applying them.

3 answers

0

The method css jQuery can receive a Javascript object, as you propose to do.

What cannot be done is to construct an object from an array the way it is in the question. But don’t worry: just create the object in a very similar way, but before calling the function. Then you pass the ready object to the function. Following example:

var definicaoCSS = {};

for (var i = 0; i < prop.length; i++) {
    var trechos = prop[i].split(':');
    definicaoCSS[trechos[0].trim()] = trechos[1].trim();
}

// quando acabar, você chama o método css
$(elemento).css(definicaoCSS);

However, it would be desirable for you to have already had object-shaped properties from the beginning. I can imagine a scenario or two where someone would set up a array before (i.e.: obtaining definitions from text boxes), but even in these scenarios it is possible to dispense with the array and do everything with object.

  • I think I’ll have problems because it’s not just simple css, it’s a keyframe. Can I use your solution anyway?/

  • I added to the end of the question where the variable came from.

  • I remember your previous question. What I wrote here should work, but I think it’s best to do a whole code Refactoring.

  • Yes Renan. But my knowledge is almost exhausted. Can you help me doing favor? Thank you!

  • @Carlosrocha the best help I can give is the answer I put here. If you are in a hurry to solve this particular problem, unfortunately it will be very difficult. But if you intend to long-term learn good practices, you need to work with more experienced people and preferably go to college in the area. It’s worth it - a few years from now you’ll reach a point where a problem like that of the question becomes trivial.

  • Hurry I have no friend! No problem. I thank you from my heart. I will give a study. It is that I suffered an accident that took my two hands. So now I’m retired for disability. And not to stop for good, I’m studying a little. But I’ve done Computer Systems Technologist at UFF. But learn really, just by doing...

Show 1 more comment

0

As you reported that the structure is still being defined, you can use json to manipulate multiple css attributes in an element.

Ex.:

var styles = {"color":"blue", "font-size":"13px"};
$("#elemento").css(styles);
  • then, look at the end of my question. Edit her and with your help, I have arrived in a situation that I do not know how to get out of. If you can help me again. The contents of my variable contain {} inside. What to do in this case?

  • I’m trying to make $("@keyframe slide"). css(Styles); It’s not working. Where I’m going wrong?

0

Please, I was able to do it the way you said, but now I have another problem:

The json object, thus printed in the log

(8) ["0% { margin-left:-0%}", "25% { margin-left:-0%}", "30% { margin-left:-100%}", "50% { margin-left:-100%}", "55% { margin-left:-200%}", "75% { margin-left:-200%}", "80% { margin-left:-300%}", "100% { margin-left:-300%}"]
0
:
"0% { margin-left:-0%}"
1
:
"25% { margin-left:-0%}"
2
:
"30% { margin-left:-100%}"
3
:
"50% { margin-left:-100%}"
4
:
"55% { margin-left:-200%}"
5
:
"75% { margin-left:-200%}"
6
:
"80% { margin-left:-300%}"
7
:
"100% { margin-left:-300%}"
length
:
8
__proto__
:
Array(0)

Now the problems are the following and are 2:

I need to launch this result as a parameter and I know two ways to do it;

To)

  $.keyframe.define([{
     name: 'tocaSlide',
    // Quando adiciono **definicaoCSS** aqui dá erro no script
  }]);        

B)

  $("body").css("@keyframe tocaSlide", function() {

    // Quando adiciono **definicaoCSS** aqui NÃO dá erro no script, mas o keyframe não recebe o style

  });

What I do now?

See the full js:

$(document).ready(function(e) {

  $("div.slider ul.slide").ready(function(e) {

      var tempoTransicao = 5;
      var quantasImagens = $("div.slider ul.slide li img").size();
      var tamanhoIntervalos = Math.round(100/quantasImagens);
      var tempoImagens = 0;
      var t = 0;    
      var imagem = "";
      var imagem2 = "";

      for (i = 0; i < quantasImagens; i++) {    

          tMin = t + tempoTransicao;
          tMax = t + tamanhoIntervalos; 
          t+=tamanhoIntervalos;

          if(i==0) tMin=0;
          if(i==quantasImagens) tMax=100;         

          imagem += tMin + "% { margin-left:-" + tempoImagens + "%},";
          imagem += tMax + "% { margin-left:-" + tempoImagens + "%},";

          imagem2 += "'" + tMin + "'% { 'margin-left':'-" + tempoImagens + "%'},";
          imagem2 += "'" + tMax + "'% { 'margin-left':'-" + tempoImagens + "%'},";

          tempoImagens+=100;

      }
      var slide = {};

      var trechos = imagem.slice(0, -1).split(',');
      var trechos2 = imagem2.slice(0, -1).split(',');
      slide[trechos2];

      //console.log(trechos);

      $.keyframe.define([{
         name: 'tocaSlide',
         slide
      }]);       

      $("<style> @keyframes tocaSlide").html(trechos);

      $("div.slider ul.slide").css({
            'animation-duration' : tempoTransicao + 's',
      });

  });

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.