使用Jquery在悬停时更改单位背景颜色

时间:2016-12-08 17:34:44

标签: javascript jquery html css

我试图在jquery中创建的div表中获取一个单元格,当我将鼠标悬停在它上面时改变颜色,并在鼠标离开单元格时保持该颜色。

我尝试添加.hover命令,但是当我添加它时,整个网格都会消失。

以下是我在JSfiddle的代码:https://jsfiddle.net/davidtaylorjr/eemLsjg7/8/

$(document).ready(function() {
  $(function() {
    for (var x = 0; x < 16; x++) {
      for (var y = 0; y < 16; y++) {
        $("<div>").addClass("unit").appendTo('#container');
      }
    }
  });
  
  $(".unit").hover() {
    $(this).css("background-color", "black");
  });
});
#container {
  background-color: lightblue;
  height: 192px;
  width: 192px;
}
.unit {
  background-color: white;
  height: 10px;
  width: 10px;
  margin: 1px;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>

2 个答案:

答案 0 :(得分:0)

除了两个语法问题之外,您的逻辑是正确的。首先,您需要提供hover()函数,以便在mousentermouseleave事件触发时执行。其次,你有嵌套的document.ready处理程序,你应该解包。修复后,它可以正常工作。

但请注意,您可以进行一些调整以改善逻辑。首先,当您在所有迭代中追加相同的HTML时,嵌套循环是多余的。你可以把它变成一个循环。其次,最好将所有样式保存在CSS中,这样您只需使用addClass()来更改背景颜色即可。最后,hover()会创建两个事件,其中代码不需要mouseleave,因此您只需使用mouseenter即可提高效率。

尽管如此,试试这个:

$(document).ready(function() {
  var html = ''
  for (var x = 0; x < 16 * 16; x++) {
    html += '<div class="unit"></div>';
  }
  $(html).appendTo('#container');

  $(".unit").mouseenter(function() {
    $(this).addClass('black');
  });
});
#container {
  background-color: lightblue;
  height: 192px;
  width: 192px;
}
.unit {
  background-color: white;
  height: 10px;
  width: 10px;
  margin: 1px;
  float: left;
}
.unit.black {
  background-color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>

另请注意,您可以完全删除循环并使用数组的fill()方法创建.unit元素:

var arr = new Array(256);
arr.fill('<div class="unit"></div>');
$('#container').html(arr.join(''));

请注意,IE和Safari不支持此功能,但MDN

可以使用填充功能

答案 1 :(得分:0)

以下内容将在鼠标进入时更改元素的背景颜色,然后取消绑定处理程序(因此代码只会在第一个mouseenter执行 - 如说明中所指定的那样)

$(".unit").mouseenter(function() {
  $(this).css("background-color", "black");
  $(this).unbind('mouseenter');
});

jQuery mouseenter文档供参考:https://api.jquery.com/mouseenter/#mouseenter-handler

更新(并为了演示而简化)小提琴:https://jsfiddle.net/eemLsjg7/9/

相关问题