2010-04-24 37 views
2

好的,這就是我正在做的。我有一個帶DISPLAY:NONE;的子元素的DIV框。我試圖使用Jquery,當鼠標進入父DIV框時,子元素變得可見,然後隱藏鼠標離開父DV時的情況。這些類會在頁面上有多個div。由於某種原因,它無法正常工作。有任何想法嗎?這裏是我的代碼:用Jquery更改不同類別的顯示器

HTML:

<div class="parent"> 
    <span class="handle" style="display: none;">My Handle</span> 
    <p>Child Text</p> 
</div> 

的Javascript:

$(document).ready(function() { 
    $('.parent').mouseenter(function(){ 
     $(this).next('.handle').show(); 
    }); 
    $('.parent').mouseleave(function(){ 
     $(this).next('.handle').hide(); 
    }); 
}) 
+0

你有沒有考慮CSS的下方唯一的解決辦法? – 2010-04-24 19:17:58

回答

3

使用find代替:

$(document).ready(function() { 
    $('.parent').mouseenter(function(){ 
     $(this).find('.handle').show(); 
    }); 
    $('.parent').mouseleave(function(){ 
     $(this).find('.handle').hide(); 
    }); 
}) 

甚至更​​好,試試這個:

$(document).ready(function() { 
    $('.parent').hover(function(){ 
     $('.handle', this).show(); 
    }, 
    function(){ 
     $('.handle', this).hide(); 
    }); 
    ); 
}) 
+0

這樣做!非常感謝! – 2010-04-24 18:55:17

+0

@John K:不客氣.......... – Sarfraz 2010-04-24 18:56:08

+0

我會建議指定元素類型。它加快了查詢的速度。 – ChaosPandion 2010-04-24 18:57:17

0

我建議您使用hover。這意味着你只需要運行一次查詢。

$('div.parent').hover(
    function() { 
     $(this).children('span.handle').show(); 
    }, 
    function() { 
     $(this).children('span.handle').hide(); 
    } 
); 
2

你可以實現你的目標沒有jQuery的:

.parent .handle{ 
    display:none; 
} 
.parent:hover .handle{ 
    display:inline; 
} 

<div class="parent"> 
    <span class="handle">My Handle</span> 
    <p>Child Text</p> 
</div> 

而且你應該使用CSS不僅是因爲它消除了對JavaScript中的需要。

測試FF和Safari

+0

這不起作用。一旦隱藏元素,我無法檢測到它。 *僅在Firefox中測試*。 – ChaosPandion 2010-04-24 19:01:40

+0

這是因爲我拼寫錯誤。再試一次。 – 2010-04-24 19:09:01

+0

我覺得真的很愚蠢。 – ChaosPandion 2010-04-24 19:18:53

0

試試這個,而是:

$(document).ready(function() { 
    $('.parent').mouseenter(function(){ 
     $(this).next('.handle').show(); 
    }).mouseleave(function(){ 
     $(this).next('.handle').hide(); 
    }); 
})