[英]Changing colour of each array element
我是HTML / CSS / JavaScript / Jquery的新手,我有一個div標記數組,這些標記表示為框。 當我將鼠標懸停在框上時,我想更改它們的顏色,但是我不確定如何訪問每個div標簽並更改其屬性。
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet3.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="script3.js"></script>
<body>
<div class="wrapper">
</div>
</body>
</head>
</html>
CSS:
body
{
background:#000;
}
.square
{
display: table-cell;
vertical-align: middle;
text-align: center;
border:2px solid #73AD21;
height: 2.5rem;
width: 2.5rem;
background-color: white;
}
Javascript / Jquery:
$(document).ready(function() {
for(i=0; i<16; i++) {
$('.wrapper').append('<div class="line">');
for(j=0; j<16; j++) {
$('.wrapper').append('<div class="square">'+j+'</div>');
}
$('.wrapper').append('</div>');
}
/*$('.wrapper').hover(function()) {
$(this).css("background","#F00");
}*/
});
當我在Javascript / Jquery部分中添加注釋行時,整個網頁都會變黑。
當我在JavaScript / jQuery部分中添加注釋行時,整個網頁都會變黑。
那是因為存在語法錯誤。 發生這種情況時,不會附加任何.square
元素,這正是您看到空白頁的原因。
.hover()
方法需要兩個函數作為參數(懸停和懸停回調)。 因此,您似乎需要以下內容:
$('.wrapper .square').hover(function() {
$(this).css("background", "#f00");
}, function() {
$(this).css("background", "#fff")
});
但是,您可以使用:hover
偽類對純CSS進行此操作。 您實際上不需要jQuery。
.square:hover {
background-color: #f00;
}
那是因為您在這行上有語法錯誤
$('.wrapper').hover(function()) {
$(this).css("background","#F00");
}
在調用$(this).css
函數之前,您要關閉懸停函數,以便所選的“ this”是主體。 它應該是:
$('.square').hover(function() {
$(this).css("background","#F00");
}, function() {
$(this).css("background","#FFF");
});
您的代碼中在注釋行上存在一些語法錯誤。
這是正確的
$(document).ready(function() {
for(i=0; i<16; i++) {
$('.wrapper').append('<div class="line">');
for(j=0; j<16; j++) {
$('.wrapper').append('<div class="square">'+j+'</div>');
}
$('.wrapper').append('</div>');
}
$('.square').hover(function() {
$(this).css("background","#F00");
},function(){
$(this).css("background","#fff");
});
});
希望你想要這個...
$(document).ready(function() { for(i=0; i<16; i++) { $('.wrapper').append('<div class="line">'); for(j=0; j<16; j++) { $('.wrapper').append('<div class="square">'+j+'</div>'); } $('.wrapper').append('</div>'); } $('.wrapper').on('hover','.square',function() { $(this).css("background","#F00"); }); $('.wrapper').on('mouseleave','.square',function() { $(this).css("background","#FFF"); }); });
body { background:#000; } .square { display: table-cell; vertical-align: middle; text-align: center; border:2px solid #73AD21; height: 2.5rem; width: 2.5rem; background-color: white; }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="stylesheet3.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="script3.js"></script> <body> <div class="wrapper"> </div> </body> </head> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.