使用javascript切换类

时间:2017-02-01 11:30:10

标签: javascript css

你好我想在用户向下滚动时将div的不透明度作为目标,当他再次向上滚动时将其删除。这是我到目前为止所获得的代码。它有效但我不明白为什么我必须在esle条件下再次遍历它,或者是他们更好的方式。只有javascript没有jquery.thank' s很多。

window.addEventListener('scroll',visible);

function visible(){
    if(window.pageYOffset>2000){
        var x = document.getElementById('wrapper').querySelectorAll('.div');
        i = 0;
        for (var i = 0 ; x.length >i; i++) {
            x[i].style.opacity = "1";
            x[i].style.transition = " 1s ease 0s ";
        }
    }else{  
        var x = document.getElementById('wrapper').querySelectorAll('.div');
        i = 0;
        for (var i = 0 ; x.length >i; i++) {
            x[i].style.opacity = "0";
            x[i].style.transition = " 1s ease 0s ";
        }
    }
}

4 个答案:

答案 0 :(得分:1)

您最好在#wrapper上设置一个班级并在CSS中进行转换:

document
  .querySelector('#wrapper')
  .classList.toggle('-isVisible', window.pageYOffset > 2000);

CSS:

#wrapper .div {
  opacity: 0;
  transition: opacity 1s ease;
}
#wrapper.-isVisible .div {
   opacity: 1;  
}

答案 1 :(得分:1)

forEach

您甚至可以使用三元运算符和window.addEventListener('scroll',visible); function visible(){ var op = window.pageYOffset > 2000? "1": "0"; // make the selector shorter too querySelectorAll('#wrapper .div').forEach(function(x){ x.style.opacity = op; x.style.transition = " 1s ease 0s "; }); } 来缩短代码:

import "github.com/apaxa-go/eval" 
...
src:="int8(1*(1+2))"
expr,err:=eval.ParseString(src,"")
if err!=nil{
    return err
}
r,err:=expr.EvalToInterface(nil)
if err!=nil{
    return err
}
fmt.Printf("%v %T", r, r)   // "3 int8"

答案 2 :(得分:0)

你是对的,你不应该把它循环两次,因为那是很多重复的代码。唯一的区别是不透明度是否设置为1或0,具体取决于滚动位置,因此您可以在循环内移动该检查:

window.addEventListener('scroll',visible);

function visible(){
    var x = document.getElementById('wrapper').querySelectorAll('.div');
    i = 0;
    for (var i = 0 ; x.length >i; i++) {
        x[i].style.opacity = window.pageYOffset>2000 ? 1 : 0;
        x[i].style.transition = " 1s ease 0s ";
    }
}

答案 3 :(得分:0)

我认为这可能会有所帮助:Fiddle

window.addEventListener('scroll',visible);

function visible(){
    var op;
    // decide what opacity will be
    if(window.pageYOffset>2000)
        op = "1";
    else
        op = "0";

    // then loop
    var x = document.getElementById('wrapper').querySelectorAll('.div');
    for (var i = 0 ; x.length >i; i++) {
        x[i].style.opacity = op; // use op here
        x[i].style.transition = " 1s ease 0s ";
    }
}

以下是原始问题:Original Question