簡體   English   中英

使用jQuery淡入然后淡出

[英]Fade in and then out using jquery

我現在才剛剛開始學習使用jQuery,並且正在嘗試淡入淡出圖像。 當我將鼠標懸停在圖像上時,我希望將其褪色至半透明。 然后,只有在我刪除了圖像的鼠標之后,圖像才恢復為完全不透明。 現在,我正在使用回調函數將圖像淡入,但它是在淡出后立即執行的,而不是在鼠標離開圖像時執行。 有人對發生的事情有任何暗示嗎?

這是我的代碼:

$(document).ready(function(){
  $("img").mouseover(function(event){
    $(this).fadeTo("fast", 0.5, function(){
      $(this).fadeTo("fast", 1.0)}
    );
  });
});

嘗試這個

$(document).ready(function(){
    $("img").on('mouseover', function(event){
        $(this).fadeTo("fast", 0.5);
    }).on('mouseout', function(){
       $(this).fadeTo("fast", 1.0)    
    });
});​

演示

您可以on使用兩個事件。 我建議不要使用hover因為它即將被棄用

$("img").on({
    mouseover: function() { $(this).fadeTo('fast', .5); },
    mouseout: function() { $(this).fadeTo('fast', 1); }
});​

http://jsfiddle.net/gT4vC/

我認為您在這里缺少班級或ID名稱。

$("img").mouseover(function(event){

而不是在$(“。img”)。mouseover(function(event){

指定鼠標懸停事件的類或ID。

用戶.hover()函數,它接受兩個參數,一個用於mouseenter事件,另一個用於mouseleave事件。

$(document).ready(function(){
    $("img").hover(function(event){
         $(this).fadeTo("fast", 0.5);
      },
      function() {
         $(this).fadeTo("fast", 1.0);
      });
});

演示

嘗試這個:

$(document).ready(function() {
    $("img").mouseenter(function(event) {
        $(this).fadeTo("fast", 0.5);
    }).mouseleave(function() {
        $(this).fadeTo("fast", 1.0);
    });
});​

演示: http//jsfiddle.net/DTzTH/

$(document).ready(function () {
  $("img").hover(function () {
    $(this).fadeTo("fast", 0.5);
  }, function () {
    $(this).fadeTo("fast", 1.0);
  });
});​

這是您要找的東西嗎? 更改頂部的大寫常量以獲得所需效果的正確時間。

$(document).ready(function(){
    var FADEOUT_TIME = 500;
    var FADEIN_TIME = 500;
    $("img").on({
        mouseleave: function() {
            $(this).fadeTo(FADEIN_TIME, 1);
        },
        mouseenter: function() {
            $(this).stop().fadeTo(FADEOUT_TIME, 0.5);
        }
    });
});

演示

是的,你可以做到

$(document).ready(function(){
    $("img").on({
    mouseover: function() { $(this).fadeTo('fast', .8); },
    mouseout: function() { $(this).fadeTo('fast', 1); }
});
});

這是js小提琴

更新資料

或者您也可以使用CSS屬性opacity

$(document).ready(function(){
    $("img").mouseover(function(){
       $('img').css('opacity','0.4');
    });

    $("img").mouseout(function(){
       $('img').css('opacity','1');
    })
});

因為這里是js小提琴

嘗試這個

$(document).ready(function(){
  $(".main").mouseenter(function(event){
      $(this).fadeTo("fast", 0.5).mouseleave(function(){
              $(this).fadeTo("fast", 1.0);
      });
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM