簡體   English   中英

在JavaScript中更改最后一個懸停

[英]Changing last li hover in javascript

我將導航欄放在一起,找到了一個不錯的腳本,可讓li在顯示第二級菜單時保持其“懸停”狀態。 在我的上一個李中,我有一個搜索欄,並希望將鼠標懸停。 碼:

<script type="text/javascript">
$(document).ready(function() {

    $("ul#topnav li").hover(function() { //Hover over event on list item
        $(this).css({ 'background' : '#7bbdc2 '}); //Add background color + image on hovered list item
        $(this).find("span").show(); //Show the subnav 
    } , 
    function() { //on hover out...
        $(this).css({ 'background' : 'none'}); //Ditch the background
        $(this).find("span").hide(); //Hide the subnav
    }); 
});
</script>    

沒有檢驗我的建議。 嘗試這個:

$("ul#topnav li:last-child").hover(nil);

按照您現有的代碼。 您的代碼將hover元素添加到#topnav中的所有li元素中,因此在此之后找到最后一個元素並將其移除。

注意:這不是最佳解決方案,因為當您在搜索下方添加一些新的li元素時,您將得到錯誤的結果。 最好為search li元素提供自己的唯一標識符,並刪除此元素上的懸停:

$("ul#topnav li#search").hover(nil);

編輯:

甚至更好-從一開始就使用不等於選擇器的屬性。

代替:

$("ul#topnav li").hover(function() {
  // ...

給你的搜索liid “搜索”,並做到這一點:

$('ul#topnav li[id!="search"]').hover(function() {
  // ...

http://api.jquery.com/attribute-not-equal-selector/

您可以從選擇器中排除元素 去做。

<script type="text/javascript">
$(document).ready(function() {

    $("ul#topnav li").not('li:last').hover(function() { //Hover over event on list item
        $(this).css({ 'background' : '#7bbdc2 '}); //Add background color + image on hovered list item
        $(this).find("span").show(); //Show the subnav 
    } , 
    function() { //on hover out...
        $(this).css({ 'background' : 'none'}); //Ditch the background
        $(this).find("span").hide(); //Hide the subnav
    }); 
});
</script>

暫無
暫無

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

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