Hovering on buttons using jquery?

2019-09-09 07:13发布

问题:

Doing a hovering event on button as below.

<div id="common_id">
<div class="button" id="make_larger">
<button type="button">Large</button> 
</div>
<div class="button" id="make_small">
<button type="button">Smaller</button> 
</div>
<div class="button" id="make_normal">
<button type="button">Normal</button> 
</div>
</div>

JQuery code is:

 $('#common_id .button').hover(function () {
            $(this).addClass('hover1');
        }, function () {
            $(this).removeClass('hover1');

        });

Css is:

.hover1 {

background-color:Black;
position:relative;

}    

When placing mouse over buttons ,the complete row(From starting to end of page) is getting black even button is not getting black but its background is seems to be black along that row. i want the button to be black when i hover on it. Why it is not working?

Thanks in advance.

回答1:

the div is taking the 100% width. so instead of selecting the div select the button. So your selector should look like this

$('#common_id .button button').hover(function () {
            $(this).addClass('hover1');
        }, function () {
            $(this).removeClass('hover1');

        });​

Try this fiddle



回答2:

Remove the jQuery entirely and use:

#common_id .button:hover {
    background-color:Black;
    position:relative;
}   


回答3:

Sohhee's answer is right,but I think the CSS script you need should be

#common_id .button botton:hover {
   background-color:Black;
   position:relative;
}


回答4:

I think the css only answer is the best - but you can select buttons on a page by using the jQuery selector $('button'), like in this example: http://jsfiddle.net/2fH7f/