2014-09-28 49 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

参考文献: