通过字符串分配translateY值

时间:2017-03-12 04:29:58

标签: javascript

我正在使用一些JavaScript来保持我的侧边栏在用户滚动页面时固定,当他到达页面的近乎底部时,然后制作侧边栏position: static。这是代码:

<script>

    window.onscroll = function() {
var px = window.scrollY;
var x = document.getElementsByClassName("sidebar");
var body = document.body,
    html = document.documentElement;
var poht = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
var poht2 = poht - 1300;

if(px < poht2){

  if(px > 1700)    
      {x[0].style.position="fixed";x[0].style.transform="translateY(-1700px)";}

  if(px < 1680){
       if(x[0].style.position=="fixed")   
         {x[0].style.position="static";x[0].style.transform="translateY(20px)";}
   }
}
       // Problem occurs here

pos2 = -1 * 2300 - poht2;
pos2 = pos2 + "px";

else {x[0].style.position="static";x[0].style.transform="translateY(pos2)";}

}
</script>

在最后一行(我的意思是else),当我想要计算一个值并将其分配给translateY()时,它不起作用。这样做的正确形式是什么?

感谢。

1 个答案:

答案 0 :(得分:2)

您可以使用字符串连接或模板文字

x[0].style.transform = "translateY(" + pos2 + ")"

x[0].style.transform = `translateY(${pos2})`