2014-09-28 48 views
1

我想用jQuery淡出和淡入帶有子元素的元素。jQuery淡出容器,但不是子女

問題是,當我淡出懸停時的父元素時,子元素隨着它消失。

如何淡入/淡出一個容器元素,但不是它的子元素,除非我將鼠標懸停在它們上面?

PS:無法使用RGBA背景色。

+3

你不能,期間! – adeneo 2014-09-28 17:19:55

+2

你不能,雖然你可以通過使用'孩子'的絕對定位給出這種幻想。 – 2014-09-28 17:20:02

回答

0

首先,根據你的問題,唯一的答案是:你不能。完全一樣。如果你隱藏祖先,孩子就會消失。

也就是說,這可以是模擬,通過使用絕對定位和模仿這些子元素;儘管這非常昂貴,而且我強烈建議,如果可能的話應該避免。但是,以下似乎滿足您的使用情況,給出以下HTML(調整的味道,很明顯):

<div class="parent"> 
    <div class="unwavering">child one</div> 
    <div class="unwavering">child two</div> 
</div> 

而jQuery的:

// creating and caching an element here, to avoid having to create 
// elements in each iteration of the 'each()' loop, later: 
var clone = $('<div />', { 
    'class': 'clone' 
}); 

// iterating over each of the child elements you want to keep visible: 
$('.unwavering').each(function() { 
    // we'll be referencing this node a few times, so we're caching it: 
    var current = $(this), 
    // we'll need this for positioning: 
     currentPosition = current.position(), 
    // getting all the computed styles of the current element: 
     css = window.getComputedStyle(this, null), 
    // getting the cssText (for the inline style): 
     styles = css.cssText, 
    // cloning the earlier-created element for use: 
     currentClone = clone.clone(); 

    // setting the 'style' attribute to the cssText: 
    currentClone.attr('style', styles).css({ 
     // overriding the following, so the clones are positioned 
     // absolutely relative to the page, not their own offset parents: 
     'position': 'absolute', 
      'top': currentPosition.top, 
      'left': currentPosition.left 
    }) 
    // setting the html of the currentClone to that of the current element 
    // (note that any duplicated ids will invalidate your HTML, and (probably) 
    // break your JavaScript: 
    .html(current.html()) 
    // setting the 'fakeParent' (made up) property: 
    .prop('fakeParent', current.parent()) 
    // appending the clone to the body: 
    .appendTo('body') 
    // binding event-handlers: 
    .on('mouseenter mouseleave', function (e) { 
     // triggering the same event-handlers on the 'fakeParent' element: 
     var target = $(this).prop('fakeParent'); 
     target.trigger(e.type); 
    });; 
}); 

// setting up the mouseenter/mouseleave event-handling: 
$('.parent').on('mouseenter mouseleave', function (e) { 
    // if the event-type (e.type) is 'mouseenter', or otherwise if 
    // the event is 'mouseleave' and the related-target is a clone, 
    // we add the 'hidden' class (jQuery won't duplicate present-classes); 
    // otherwise we remove the 'hidden' class: 
    $(this)[(e.type === 'mouseenter') || (e.type === 'mouseleave' && $(e.relatedTarget).is('.clone')) ? 'addClass' : 'removeClass']('hidden'); 
}); 

JS Fiddle demo

參考文獻: