2013-06-25 52 views
0

我有一個綠色的孩子紅色的div,綠色的鼠標懸停在它的父母移動。很簡單。使子元素消失它的父`mouseleave`

HTML:

<div class="big"> 
    <div class="small"></div> 
</div> 

CSS:

.big { 
    position: relative; 
    width: 200px; height: 200px; 
    margin: 20px auto; 
    background: red; 
} 

.big:hover .small { 
    opacity: 1; 
} 

.small { 
    position: absolute; 
    top: 0; left: 0; 
    width: 50px; height: 50px; 
    background: green; 
    opacity: 0; 
} 

的JavaScript:

$('.big').on('mousemove', function (e) { 

    var $this = $(this), 
     small = $this.find('.small'), 
     offset = $this.offset(), 
     cursorX = e.pageX - offset.left, 
     cursorY = e.pageY - offset.top, 
     smallX = cursorX - small.width()/2, 
     smallY = cursorY - small.height()/2; 

    $('.small').css({ 
     top: smallY, 
     left: smallX 
    }); 

}); 

如何使綠色框,當它離開紅色的消失? :hover在CSS中不起作用,因爲綠色div是紅色的一部分(我是quess),所以光標永遠不會離開它。只有當你迅速移動它時,綠色的div才能跟上光標和消聲器。也許增加一些具有特定定位的包裝元素將會有所斬獲?或者像jQuery stopPropagation()

這裏是我的Fiddle

UPDATE:這裏的updated code,基於從用戶沒關係建議。我添加了一個轉換,它隨着我想要的消失,但現在還有其他問題。當光標快速移動到紅色框外時,綠色框將停留在其父項的邊框上。

回答

0

代替mousemove嘗試mouseover

DEMO

+0

我需要更多的流體運動,就像'mousemove'一樣 –

1

我想這是你想要什麼:

http://jsbin.com/obewaz/1/

http://jsbin.com/obewaz/1/edit

相同的HTML/CSS,添加在jQuery的幾個:

$(document).ready(function() { 

$('.big').on('mousemove', function (e) { 



    var $this = $(this), 
     smalle = $this.find('.small'), 
     offset = $this.offset(), 
     position=smalle.position(), 
     cursorX = e.pageX - offset.left, 
     cursorY = e.pageY - offset.top, 
     smallX = cursorX - smalle.width()/2, 
     smallY = cursorY - smalle.height()/2; 

    $('.small').css({ 
     top: smallY, 
     left: smallX 
    }); 

console.log(position); 

if(position.left<0 || position.left>150 || position.top<0 || position.top>150) { 
    $('.small').css('display','none'); 
} 
else { 

$('.small').css('display','block'); 
} 


}); 
}); 

當然,您可以在最後一個條件中更改/調整值以適合您的需要。想法是:追蹤小盒子的位置,當它位於大盒子的「外面」時 - 隱藏它。

+0

我在想這樣的事情,我會嘗試更新我的代碼,並且可能會添加一些不透明度轉換,因爲這將在最終項目中。 –