簡體   English   中英

將鼠標懸停在另一個id上時,使用removeClass

[英]removeClass when hover over a different id

這是我編寫的代碼。 將鼠標懸停在第一個項目上時,它會添加一個類,並且該類具有背景圖像,並且還會添加html來解釋從懸停顯示的圖像。 當我將鼠標懸停在下一個項目上時,就會發生此問題,它取代了以前的懸停中顯示的舊信息,並帶有一個新的addclass圖像,以及一個新的html來解釋顯示的新圖像。 因此,如果我返回第一個項目,它將不會替換圖像。 我確定我需要某種方式的removeClass,但是如果有適當的地方,我希望它告訴它刪除類。 這是代碼:

  function imageInfo(){
    $('#item_one').hover(function(){
        $('#img_holder').addClass('img_one');
        $('#about_me_cont aside p').html('text explaining img 1');
    });
    $('#item_three').hover(function(){
        $('#img_holder').addClass('img_two');
        $('#about_me_cont aside p').html('text explaining img 2');
    });
    $('#item_three').hover(function(){
        $('#img_holder').addClass('img_three');
        $('#about_me_cont aside p').html('text explaining img 3');
    });
  }

這是CSS:

.img_one{
    background-image: url('../images/img1.jpg');
    background-repeat: no-repeat;
    background-size:contain;
}
.img_two{
        background-image: url('../images/img2.jpg');
        background-repeat: no-repeat;
        background-size:contain;
}
.img_three{
    background-image: url('../images/img3.jpg');
    background-repeat: no-repeat;
    background-size:contain;
}

html插入了一段,然后在CSS中設置了樣式。 因此,當我將鼠標懸停在項目1上,然后轉到項目2,然后返回到項目1之后,會發生什么情況,它將項目2的圖像保留在那里,html更改了,但是項目2的圖像卻沒有。 如果那里有一個類,我將如何為removeClass編寫它,以便返回到再次顯示第一個項目圖像? 感謝您的幫助!

您的代碼中有錯別字:應該在哪里

$('#item_two').hover(function(){

它改為表示item_three。

就是說,即使沒有類,使用jQuery removeClass函數也沒錯,它不會失敗。 因此,您可以執行以下操作:

function imageInfo(){
    $('#item_one').hover(function(){
        $('#img_holder').removeClass().addClass('img_one');
        $('#about_me_cont aside p').html('text explaining img 1');
    });
    $('#item_three').hover(function(){
        $('#img_holder').removeClass().addClass('img_two');
        $('#about_me_cont aside p').html('text explaining img 2');
    });
    $('#item_three').hover(function(){
        $('#img_holder').removeClass().addClass('img_three');
        $('#about_me_cont aside p').html('text explaining img 3');
    });
  }

暫無
暫無

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

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