使用jQuery循环设置css属性

use jQuery loop to set css properties

本文关键字:css 属性 设置 循环 jQuery 使用      更新时间:2023-09-26

我正试图使用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>

所以我希望每个类都有一个不同位置的背景图像。目前,它们都以300像素的高度堆叠在顶部。

感谢

因此,我在循环中放置了一个console.log(leftTabHeight),它确实打印了0100200300。300是唯一应用的。

您可以执行以下操作:

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

这是假设需要它的对象具有类"background_image"。

好吧,我已经发现问题是,每次函数循环时,我都会重写所有的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'});
};

问题是您引用了所有".left.main“项。将这些行更改为$('.'+pageArray[p]+'.left.main').css(...),就这样。