我想使用jQuery淡出和淡化带有子元素的元素。
问题在于,当我在悬停时淡出父元素时,子元素会随之淡化。
除非我将鼠标悬停在它们上面,否则我如何淡化/淡出一个容器元素,而不是它的子元素?
PS:不能使用RGBA,背景色。
答案 0 :(得分: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');
});
参考文献:
addClass()
。appendTo()
。attr()
。clone()
。each()
。html()
。is()
。on()
。position()
。prop()
。removeClass()
。trigger()
。