使用jquery悬停增加div的不透明度

时间:2014-05-21 22:09:14

标签: javascript jquery html css opacity

我正在使用jquery悬停来逐渐增加div的网格中的div的不透明度,鼠标在每个div上传递。出于某种原因,当我添加一个增量时,比如说我已经包含不透明度的变量为0.1,而不是从1.1223408变为2.1223408,它增加到1.12234080.1。它几乎像是把它当成字符串而不是数字?

我想要开始工作的代码是:

function opacity(){

    $('.cell').css("backgroundColor", "black");
    $('.cell').css("opacity", 0);

    $('.cell').hover(function(){

    var value = $(this).css("opacity");

    if(value<1){
        value += 0.1;   
        $(this).css("opacity", value);
    }
}

我能让它像我想要的那样工作的唯一方法是非常不优雅:

function opacity(){

$('.cell').css("backgroundColor", "black");
$('.cell').css("opacity", 0);

$('.cell').hover(function(){

    var value = $(this).css("opacity");

    if(value==0){
        value = 0.1;    
        $(this).css("opacity", value);
    }
    else if (0.1 < value < 0.2){
        value = 0.2;
        $(this).css("opacity", value);
    }
    else if (0.2 < value < 0.3){
        value = 0.3;
        $(this).css("opacity", value);
    }
    else if (0.3< value < 0.4){
        value = 0.4;
        $(this).css("opacity", value);
    }
    else if (0.4< value < 0.5){
        value = 0.5;
        $(this).css("opacity", value);
    }
    else if (0.5 < value < 0.6){
        value = 0.6;
        $(this).css("opacity", value);
    }
    else if (0.6 < value < 0.7){
        value = 0.7;
        $(this).css("opacity", value);
    }
    else if (0.7 < value < 0.8){
        value = 0.8;
        $(this).css("opacity", value);
    }

}, function(){

    value -= 0.15;
    $(this).css("opacity", value)
});

}

为什么第一个解决方案没有工作?

3 个答案:

答案 0 :(得分:3)

.css("opacity")将返回字符串。因此,在执行某些数学运算之前,必须使用parseFloat将其转换为数值。

$('.cell').hover(function(){
  var value = parseFloat($(this).css("opacity"));    
  if(value<1){
    value += 0.1;           
    $(this).css("opacity", value);
  }
});

每次触发悬停时,您也可以使用+=0.1作为opacity的值,不要担心不透明度会超过1值,这会赢得&#39发生了。在内部,其最大值始终为1

$('.cell').hover(function(){
  $(this).css("opacity", "+=0.1");
});

答案 1 :(得分:1)

您的代码中的悬停功能似乎缺少一个末端支架/支架,请参阅下文:

function opacity(){

  $('.cell').css("backgroundColor", "black");
  $('.cell').css("opacity", 0);

  $('.cell').hover(function(){
    var value = $(this).css("opacity");

    if(value<1){
        value += 0.1;   
        $(this).css("opacity", value);
    }
  }, function(){
    //do something on mouseout
  });

}

答案 2 :(得分:0)

你很有可能把它作为一个字符串。为确保您获得正确的类型,请使用parseFloat。此外,如果您将起始不透明度更改为其他数字,您可以将悬停功能钳位设为1,这样如果从0.5开始它不会停在0.95。

function opacity() {

    $('.cell').css("backgroundColor", "black");
    $('.cell').css("opacity", 0);

    $('.cell').hover( function() {

       var value = parseFloat($(this).css("opacity"));
       value += 0.1;
       $(this).css("opacity", Math.min(value, 1));

    });

}