簡體   English   中英

使用Jquery在懸停時更改單位背景顏色

[英]Change Unit Background Color on hover using Jquery

我試圖在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> 

除了兩個語法問題之外,您的邏輯是正確的。 首先,你需要提供一個函數來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(''));

請注意,雖然在MDN上提供了polyfill,但在IE和Safari中不支持此功能

當鼠標進入時,以下內容將更改元素的背景顏色,並隨后取消綁定處理程序(因此代碼將僅在第一個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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM