使用jQuery循环来设置css属性

时间:2012-03-17 06:39:36

标签: javascript jquery css variables loops

我正在尝试使用jQuery循环来设置一个变量,该变量将在每次循环中发生变化。然后将变量应用于css属性。我遇到的问题是每个带变量的css属性都有相同的值(这是循环结束时的值)。

pageArray = new Array('web1','web2','web3','web4');
    **leftTabHeight** = 0;
for (var p=0;p<pageArray.length;p++){
    **leftTabHeight** = parseFloat(p) *100;
    $('.left.main').addClass('flip_left');
    $('.left.main').css({'width':'482px', 'height':'668px', 'z-index':'11','background':'url("images/snake_tab.png") no-repeat, url("images/book_left_main.png") no-repeat','background-position': '0px '+**leftTabHeight**+'px, 42px 42px','position':'absolute'});

};

HTML:

<div class="web4 left main">
    <h3 class="left_button">web 4</h3>
<h4>web 4</h4>
<p>Stuff</p>
</div>
<div class="web4 left bind">    
</div>

<div class="web3 left main">
<h3 class="left_button">web 3</h3>
<h4>web 3</h4>
<p>stuff</p>
</div>
<div class="web3 left bind">    
</div>

<div class="web2 left main">
<h3 class="left_button">web 2</h3>
<h4>web 2</h4>
<p>Stuff</p>
</div>
<div class="web2 left bind">    
</div>

<div class="web1 left main">
<h3 class="left_button">web 1</h3>
<h4>web 1</h4>
<p>Stuff</p>
</div> 
<div class="web1 left bind">    
</div>

所以我希望每个班级的背景图片都有不同的位置。目前它们都以300px排在最前面。

由于

所以,我在循环中放置了一个console.log(leftTabHeight),它确实打印了0,100,200,300。300是唯一被应用的。

3 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

var variable_position = 0;
$('.background_image').each(function(){
  $(this).css('background-position', '0px ' + variable_position + 'px 42px 42px');
  variable_position += 100;
});

假设你需要它的对象有“background_image”类。

答案 1 :(得分:0)

好吧我已经弄明白了问题是我每次函数循环它重写了所有的div。我需要将第三个类添加到jQuery选择中作为变量。所以这段代码有效:

pageArray = new Array('snake','web_s','web1','web2','web3','web4');
var leftTabHeight = 0;
for (var p in pageArray){
    leftTabHeight = parseFloat(p *100);
    $('.'+pageArray[p]+'.left.main').addClass('flip_left');
    $('.'+pageArray[p]+'.left.main').css({'width':'482px', 'height':'668px', 'z-index':'11','background':'url("images/snake_tab.png") no-repeat, url("images/book_left_main.png") no-repeat','background-position': '0px '+leftTabHeight+'px, 42px 42px','position':'absolute'});
};

答案 2 :(得分:0)

问题是您指的是所有".left.main“项。将这些行更改为$('.'+pageArray[p]+'.left.main').css(...)即可。

相关问题