【发布时间】:2014-11-23 02:42:15
【问题描述】:
我想使用 jQuery 淡出和淡入带有子元素的元素。
问题是当我在悬停时淡出父元素时,子元素也会随之淡出。
我怎样才能淡入/淡出一个容器元素,而不是它的子元素,除非我将鼠标悬停在它们上面?
PS:不能使用 RGBA,背景色。
【问题讨论】:
-
你不能,尽管你可以通过使用“孩子”的绝对定位来产生这种错觉。
我想使用 jQuery 淡出和淡入带有子元素的元素。
问题是当我在悬停时淡出父元素时,子元素也会随之淡出。
我怎样才能淡入/淡出一个容器元素,而不是它的子元素,除非我将鼠标悬停在它们上面?
PS:不能使用 RGBA,背景色。
【问题讨论】:
首先,根据您的问题,唯一的答案是:您不能。完全没有。如果你隐藏祖先,孩子就会消失。
也就是说,这可以通过使用绝对定位和模仿那些子元素来模拟;虽然这是相当昂贵的,我强烈建议,如果可能的话,应该避免。但是,考虑到以下 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');
});
参考资料:
addClass()。appendTo()。attr()。clone()。each()。html()。is()。on()。position()。prop()。removeClass()。trigger()。【讨论】: