简体   繁体   中英

get style from css, JavaScript

I making JavaScript 3D animation using actual style. I create working code but, i can't run the code if style is in extended CSS file, so code run only when style is written in HTML code. There is a solution?

Working code (olso on fiddle) :

HTML

<div id="background">
   <div class="example" style="transform-origin: 50% 50% -200px">
      <p class="num">Example</p>
   </div>
<div>

CSS

body {
  display: inline-block;
  background-color: black;
  box-sizing: border-box;
}
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.example {
  display: inline-block;
  position: absolute;
  color: orange;
  width: 100%;
  font-size: 30px;
  overflow: hidden;
  white-space: nowrap;
  font-size: 80px;
}

#background{
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: absolute;    
}

.example:nth-child(1){
   transform: perspective(200px);
   transform-origin: 50% 50% -200px;
}


.background {
  display: inline-block;
  position: absolute;
  width: 100%;
  height: 100%;
  border-style: solid;

}

.num {
  display: inline-block;
  color: orange;
  width: 50px;
  height: 50px;
  text-align: center;


}

JavaScript

setInterval(function(){ move()}, 2000);

function move(){    
   var elem = document.getElementsByClassName("example");
   var str = elem[0].style.transformOrigin;
   var res = str.split(" ");
   var pos = res[2].replace(/px/g, " ");
   var id = setInterval(frame, 20);

   function frame(){
     if (pos==500){
     clearInterval(id);
   }
   else {
    pos++;
    elem[0].style.transformOrigin = "50% 50%"+pos+"px";
   }
 }                                                                      
}

So as you see everything is working but, when i delete style from HTML code. I can see error in console: Cannot read property 'replace' of undefined

You need to use getComputedStyles . That will allow you to see the CSS computed values. JS is not able to extract the CSS stylings directly from the DOM element, but needs to process the styles that has been applied to it.

Also you will need to use getPropertyValue('transform-origin') in order to access the desired attribute.

Your assign to str in order to get the 3rd value of the transform origin will look like:

    var str = getComputedStyle(elem[0]).getPropertyValue('transform-origin')

Fiddle here

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