简体   繁体   English

在jQuery中将鼠标悬停时更改CSS选择器子级

[英]Change a CSS selectors child on hover in jQuery

With this basic jQuery code below, how would I make the on mousout change the item back to display:none ? 使用下面的基本jQuery代码,我如何使mousout将项目改回display:none

Also can this be improved? 还可以改善吗?

Any help please 任何帮助请

$(".image").hover(function() {
      $(this).children(".image p").css({ display: 'inline' });
});

On the jQuery docs site I saw this: $(selector).hover(handlerIn, handlerOut) but I don't understand how to apply it here. 在jQuery docs网站上,我看到了: $(selector).hover(handlerIn, handlerOut)但我不知道如何在此处应用它。

$(".image").hover(function() {
      $(this).children(".image p").show();
}, function() {
      $(this).children(".image p").hide();
});

But why not use pure CSS for it? 但是为什么不使用纯CSS呢?

.image:hover .image p { display:inline; }

You don't need 2 functions if you test the event: 如果您测试事件,则不需要2个函数:

$(".image").hover(function(e) {
      $(this).children("p").toggle(e.type === 'mouseenter');
});

Here's a demo: http://jsfiddle.net/U5QGU/ 这是一个演示: http : //jsfiddle.net/U5QGU/

I also simplified the selector because you don't need: 我还简化了选择器,因为您不需要:

.image p

Because you already know that its parent has .image 因为您已经知道其父项具有.image

You could also do this instead of toggle: 您也可以这样做,而不是切换:

$(".image").hover(function(e) {
      $(this).children("p")[e.type === 'mouseenter' ? 'show' : 'hide']();
});

http://jsfiddle.net/U5QGU/1/ http://jsfiddle.net/U5QGU/1/

ThiefMaster is correct also but this is exactly as you asked for it: ThiefMaster也是正确的,但这正是您所要求的:

$(".image").hover(function() {
      $(this).children(".image p").css({display:'inline'});
}, function() {
      $(this).children(".image p").css({display:'none'});
});

An alternative to using children is to provide selector context: 使用子代的替代方法是提供选择器上下文:

$(".image").hover(function() {
    $("p", this).css({ display:'visible' });
}, function() {
    $("p", this).css({ display:'none' });
});

To use a single function as suggested by shredder: 要使用碎纸机建议的单个功能:

$(".image").hover(function(e) {
    var d = (e.type === 'mouseenter') ? 'visible' : 'none';
    $("p", this).css({ display: d });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM