我尝试使用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是唯一应用的版本。
发布于 2012-03-17 14:54:21
你可以这样做:
var variable_position = 0;
$('.background_image').each(function(){
$(this).css('background-position', '0px ' + variable_position + 'px 42px 42px');
variable_position += 100;
});这是假设您的对象需要"background_image“类。
发布于 2012-03-17 23:22:28
好的,我已经弄清楚了,问题是,每次函数循环的时候,都会重写所有的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'});
};发布于 2012-03-18 00:15:38
问题是您引用的是所有的".left.main“项。将这些行更改为$('.'+pageArray[p]+'.left.main').css(...),就是这样。
https://stackoverflow.com/questions/9747904
复制相似问题