如何在jQuery中将属性设置为百分比?

时间:2018-06-24 12:07:17

标签: javascript jquery css css-selectors percentage

我无法在jQuery中设置CSS属性{left: $numberEquivalentToPercent}

var targets = $('.parallax__layer__cell');
var i = 1;
for(i = 1; i <= targets.length; i++)
{
  if (targets.parents('.parallax__layer--bg').length) {
//apply to only those element that have a parent having class "parallax__layer--bg"
    targets.eq(i).css('left', toString(60*i)+  "%");
  }
}

上面的代码(在JS中)有望产生与下面的效果(在CSS中)

.parallax__layer__cell:nth-child(1) { left: 0%; }
.parallax__layer__cell:nth-child(2) { left: 60%; }
.parallax__layer__cell:nth-child(3) { left: 120%; }
.parallax__layer__cell:nth-child(4) { left: 180%; }
.parallax__layer__cell:nth-child(5) { left: 240%; }

基本上我正在尝试将静态代码转换为动态代码

3 个答案:

答案 0 :(得分:0)

这是工作代码:

var targets = $('.parallax__layer__cell');
var i ;
 for(i = 0; i < targets.length; i++)
{
  if (targets.eq(i).parents('div.parallax__layer--bg').length) {
          targets.eq(i).css('left', 60*i +  "%");
   }
}
.parallax__layer__cell{
position:absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
  <div class="parallax__layer--bg">
    <div class="parallax__layer__cell">a</div>
  </div> 

  <div class="parallax__layer--bg">
    <div class="parallax__layer__cell">b</div>
  </div>

  <div class="parallax__layer--bg">
    <div class="parallax__layer__cell">c</div>
  </div>

  <div class="parallax__layer--bg">
    <div class="parallax__layer__cell">d</div>
  </div>

  <div class="parallax__layer--bg">
    <div class="parallax__layer__cell">e</div>
  </div>

  <div>
    <div class="parallax__layer__cell">--no parent--</div>
  </div>
</div>

答案 1 :(得分:0)

如果将60 * i放入名为numPercent的变量,然后执行numPercent.toString()将其转换为字符串怎么办?

var targets = $('.parallax__layer__cell');
var i = 1;
for(i = 1; i <= targets.length; i++)
{
  if (targets.parents('.parallax__layer--bg').length) {
//apply to only those element that have a parent having class "parallax__layer--bg"
    var numPercent = 60*i;
    targets.eq(i).css('left', numPercent.toString() +  "%");
  }
}

答案 2 :(得分:0)

我相信这是视差脚本和脚本之间的时间问题。由于css加载的第一个视差脚本工作正常。但是,如果删除css并在视差脚本之后运行脚本,则可能不会达到相同的效果。确保您的脚本在实际的视差脚本之前运行。