jQuery hover和类选择器 [英] jQuery hover and class selector
本文介绍了jQuery hover和类选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法使用以下HTML,CSS和javascript动态更改div的背景颜色。
HTML:
I wan't to change the background color of a div dynamicly using the following HTML, CSS and javascript. HTML:
<div id="menu">
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
<div class="menuItem"><a href=#>Bla</a></div>
</div>
CSS:
.menuItem{
display:inline;
height:30px;
width:100px;
background-color:#000;
Javascript:
Javascript:
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
编辑:我忘记说我有理由不想使用css方式。
I forgot to say that I had reasons not to want to use the css way.
我确实忘了检查是否加载了DOM。
And I indeed forgot to check if the DOM was loaded.
推荐答案
您的代码对我来说很好。
Your code looks fine to me.
使用jQuery的$(callback)函数确保DOM已经准备就绪: / p>
Make sure the DOM is ready before your javascript is executed by using jQuery's $(callback) function:
$(function() {
$('.menuItem').hover( function(){
$(this).css('background-color', '#F00');
},
function(){
$(this).css('background-color', '#000');
});
});
这篇关于jQuery hover和类选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文