我想在循环中保存变量的值并继续使用它,但是我不知道如何做
function slide(){
var picter = document.getElementsByClassName("picter");
var g=0;
var c=0;
for(var i=0;i<picter.length;i++){
if(getComputedStyle(picter[i]).opacity == 1){
picter[g].style.opacity = 0;
g+=1;
picter[g].style.opacity = 1;
break;
}
}
//alert(g);
}
<div class="slider" >
<a class="back arrow" onclick="slide()">Back</a>
<div class="picterSlider">
<div class="picter picterLeft">Left</div>
<div class="picter picterCenter">Center</div>
<div class="picter picterRight">Right</div>
</div>
<a class="next arrow" onclick="slide()">Next</a>
</div>
我试图设置为另一个变量,但是它不起作用(
答案 0 :(得分:0)
您可以将变量设置为全局变量
var picter;
var g=0;
var c=0;
function slide(){
= document.getElementsByClassName("picter");
for(var i=0;i<picter.length;i++){
if(getComputedStyle(picter[i]).opacity == 1){
picter[g].style.opacity = 0;
g+=1;
picter[g].style.opacity = 1;
break;
}
}
//alert(g);
}
<div class="slider" >
<a class="back arrow" onclick="slide()">Back</a>
<div class="picterSlider">
<div class="picter picterLeft">Left</div>
<div class="picter picterCenter">Center</div>
<div class="picter picterRight">Right</div>
</div>
<a class="next arrow" onclick="slide()">Next</a>
</div>
或者您也可以将变量的值保存到localstorage
中。而且每次您想使用时,都可以从localstograte
答案 1 :(得分:0)
我想我知道您要在这里做什么,您可以在摘要中查看评论,并且很乐意回答您的任何问题。
// Define g globally
var g = 0;
function slide(increment) {
var picter = document.getElementsByClassName("picter");
var c = 0;
for (var i = 0; i < picter.length; i++) {
if (getComputedStyle(picter[i]).opacity == 1) {
picter[g].style.opacity = 0;
g += increment;
// Make sure g doesn't get below 0
g = g < 0 ? 0 : g;
// Make sure g doesn't go beyond the last element
g = g > picter.length - 1 ? picter.length - 1 : g;
picter[g].style.opacity = 1;
break;
}
}
alert(g);
}
<div class="slider">
<a class="back arrow" onclick="slide(-1)">Back</a>
<div class="picterSlider">
<div class="picter picterLeft">Left</div>
<div class="picter picterCenter">Center</div>
<div class="picter picterRight">Right</div>
</div>
<a class="next arrow" onclick="slide(1)">Next</a>
</div>