Changing A Different Class Display on Hover with Jquery
Ok, here's what I'm trying to do. I have a DIV box with a child element se开发者_Python百科t with DISPLAY: NONE;. I'm trying to use Jquery so that when the mouse enters the parent DIV box, the child element is made visible, and then hides when the mouse leaves the parent DV. There will be multiple divs on the page with these classes. For some reason it's not working. Any ideas? Here's my code:
HTML:
<div class="parent">
<span class="handle" style="display: none;">My Handle</span>
<p>Child Text</p>
</div>
Javascript:
$(document).ready(function () {
$('.parent').mouseenter(function(){
$(this).next('.handle').show();
});
$('.parent').mouseleave(function(){
$(this).next('.handle').hide();
});
})
Use find
instead:
$(document).ready(function () {
$('.parent').mouseenter(function(){
$(this).find('.handle').show();
});
$('.parent').mouseleave(function(){
$(this).find('.handle').hide();
});
})
Or even better, try this:
$(document).ready(function () {
$('.parent').hover(function(){
$('.handle', this).show();
},
function(){
$('.handle', this).hide();
});
);
})
You can achieve your goal without jQuery:
.parent .handle{
display:none;
}
.parent:hover .handle{
display:inline;
}
<div class="parent">
<span class="handle">My Handle</span>
<p>Child Text</p>
</div>
And you should probably use CSS only because it removes the need for Javascript.
Tested FF and Safari
I recommend you use hover
. This means you only need to run the query once.
$('div.parent').hover(
function () {
$(this).children('span.handle').show();
},
function () {
$(this).children('span.handle').hide();
}
);
Try this, instead:
$(document).ready(function () {
$('.parent').mouseenter(function(){
$(this).next('.handle').show();
}).mouseleave(function(){
$(this).next('.handle').hide();
});
})
精彩评论