2015-10-11 17 views
4

如果您點擊並且不移動鼠標,您將看到按鈕的顏色保持爲紅色! 我想要完成的是在您單擊並且不移動鼠標之後,它仍然移除/切換.hover類。如何刪除/切換元素上的懸停類(單擊後翻譯),而無需再次移動鼠標?

Example on jsFiddle

$(function() { 
 
    var $Btn = $('.button'); 
 

 
    $Btn.hover(function() { 
 
    $(this).toggleClass("hover"); 
 
    }); 
 

 

 
    $Btn.on("click", function() { 
 
    $(this).toggleClass('active') 
 
    $('.move').toggleClass('angle'); 
 
    }); 
 
});
.move { 
 
    border: 1px solid #000000; 
 
    padding: 10px; 
 
    transition: transform .2s ease; 
 
    /* 
 
     have noticed issue is in "transition" 
 
    */ 
 
} 
 
.button.hover { 
 
    color: red; 
 
} 
 
.angle { 
 
    transform: translate(100px, 0); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="move"> 
 
    <button class="button">on click still red?</button> 
 
</div>

+2

是[這](http://jsfiddle.net/d795jt5o/),你需要什麼? – Harry

+1

謝謝! @哈里 [結果非常棒!](http://robylayouts.com/file/btn-bug.gif) –

回答

3

元素被保留hover類的按鈕被點擊後也(和容器被翻譯),因爲瀏覽器似乎並沒有被調用hover- (或鼠標移出),直到鼠標實際移動。

解決此問題的一種方法是刪除按鈕的click事件處理程序中的hover類。但爲了實現這個功能,hover事件處理程序的代碼需要更改爲在mouseover(hover-in)上專門添加類,並在鼠標移出(懸停)時將其刪除。這是必要的,因爲儘管hover類在click事件處理程序中被刪除,但在鼠標再次移動的時候會被切換回來(因爲在那個時間點,hover的處理程序沒有看到類在元素上)。

的變化其實也可以在兩種方式的代碼 - 或者通過(在我原來的小提琴等),或通過將兩個單獨的函數來hover處理程序使用單獨的mouseovermouseout功能。當兩個函數通過時,第一個函數被懸停在第二個函數上,第二個函數被懸停在外面。

$(function() { 
 
    var $Btn = $('.button'); 
 

 
    $Btn.hover(function() { 
 
    $(this).addClass("hover"); 
 
    },function() { 
 
    $(this).removeClass("hover"); 
 
    }); /* first function is executed on mouseover, second on mouseout */ 
 

 
    $Btn.on("click", function() { 
 
    $(this).removeClass('hover'); // remove the hover class when button is clicked 
 
    $('.move').toggleClass('angle'); 
 
    }); 
 
});
.move { 
 
    border:1px solid #000000; 
 
    padding: 10px; 
 
    transition: transform .2s ease; 
 
    /* 
 
    have noticed issue is in "transition" 
 
    */ 
 
} 
 
.button.hover { 
 
    color: red; 
 
} 
 
.angle { 
 
    transform: translate(100px, 0); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="move"> 
 
    <button class="button">on click still red?</button> 
 
</div>

相關問題