Ian*_*Ian 5 css jquery mouseover opacity mouseout
我在网格上有9个项目,我希望所有项目在每个项目上都有0.5个不透明度,并且只有在盘旋时,div/item和内部的所有内容都有1.0 opacicty.
这是JS
$('.gallery-single').css({ opacity: 0.5 });
$('.gallery-single a').mouseover(function(){
$('.gallery-single-title', this).css('display', 'block');
$('.gallery-single', this).css({ opacity: 1 });
});
$('.gallery-single a').mouseout(function(){
$('.gallery-single-title', this).css('display', 'none');
$('.gallery-single', this).css({ opacity: 0.5 });
});
Run Code Online (Sandbox Code Playgroud)
HTML
<div class="gallery-single">
<a href="#" title="">
<div class="gallery-single-title hide">Some text goes here</div>
<div class="gallery-single-img"><img src="http://img.youtube.com/vi/code/0.jpg" width="300" height="200" /></div>
</a>
</div>
Run Code Online (Sandbox Code Playgroud)
加载时所有项目的不透明度均为0.5,但聚焦时不会更改不透明度.我在这做错了什么?
试试这个:
$('.gallery-single a').hover(function(){
$(this).closest('.gallery-single-title').css('display', 'block');
$(this).closest('.gallery-single').css({ opacity: 1 });
},
function(){
$(this).closest('.gallery-single-title').css('display', 'none');
$(this).closest('.gallery-single').css({ opacity: 0.5 });
});
Run Code Online (Sandbox Code Playgroud)
工作实例.
问题是.gallery-single是锚点的祖先(即它在锚点之外)。该格式在 中$(selector, this)查找选择器。相反,使用: this.closest()
$(this).closest('.gallery-single').css(...);
Run Code Online (Sandbox Code Playgroud)
旁注:jQuery 给出了以下警告mouseover(也适用于mouseout):
由于事件冒泡,这种事件类型可能会引起许多令人头痛的问题。例如,当鼠标指针移到本例中的 Inner 元素上时,将向该元素发送 mouseover 事件,然后向上滴到 Outer 元素。这可能会在不适当的时候触发我们绑定的鼠标悬停处理程序。请参阅 .mouseenter() 的讨论以获取有用的替代方案。
您应该使用mouseenter(和mouseleave) 代替(或hover()方便地将两者结合起来的函数)。