0

我有一个网格生成器,它使用 Javascript 和 jQuery 在网格中生成以 HTML 和 CSS 显示的块。我正在尝试设置一个按钮来更改块的 :hover 行为(特别是更改它们的背景颜色)。我无法做到这一点,我不确定为什么我的代码不起作用。我将在这里复制并粘贴它,我很抱歉它很长。你可以在这里看到它的实际效果:http: //codepen.io/anon/pen

HTML

<html>
<head>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="script.js"></script>
 <title> Odin #2 by Max Pleaner </title>
<link rel="stylesheet" type="text/css" href='stylesheet.css'>
</head>

<body>
<p> Welcome to my Odin Project #2 page. This is me showing off my basic JS and jQuery skills. If you move your mouse through the blocks you can see frogs come out of hiding. If you press the clear button below you can select a new number of blocks to fill the same space.</p>
<button id="button"> Generate a number of blocks of your liking that will position themselves to all fit in the 960px by 960px grid.  </button>
<button id="button2"> <strike> Click here to generate new blocks and make hovering on blocks produce random colors.</strike> Why isn't this button working?! It's drawing new blocks fine, but not changing the :hover style as intended. </button>



<div id="square_holder">
</div>
<img src="Q6w802v.jpg" alt="froggy" ></img>
</body>

</html>

CSS

body {
background-color: grey;
}

p {
color: aqua;
}

#square_holder {
width: 960px;
}

.block {
background-color: green;
display:inline-block;
border: 1px solid black;
width: 232px;
height: 232px;
}

.block:hover {
background-color: blue;
//background-image:url("Q6w802v.jpg");
background-size: contain;
}

JS

$(document).ready(function(){

  draw_grid(4);



  $('#button').click(function(){
      get_input();
  });

 $('#button2').click(function(){
        get_input();
        $('.block:hover').css("background-image", "none").css("background-color", get_random_color());

    }); 

});
 var draw_grid = function (blocks) {
        var totalno = Math.pow(blocks, 2);
        var dimension = (960 - 1 -(blocks * 2))/blocks;
        for(var i = 0; i < totalno; i++){
            $("#square_holder").append("<div class='block' id=" + i + "></div>");
        };
    $(".block").css("height", dimension).css("width", dimension);
    }


var get_input = function(){
        alert('Do you want to change the number of boxes?<b></b>');
    $('#square_holder').empty();
    var user_entry = prompt("What number do you choose?"); 
    alert("Watch in awe as the grid fills ..... ");
    draw_grid(user_entry);
    }


 var get_random_color = function() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
};
4

1 回答 1

2

你需要使用background,而不是background-color。取自背景图像的 MDN 页面

CSS background-image 属性为一个元素设置一个或多个背景图像。图像被绘制在连续的堆叠上下文层上,第一个指定的被绘制就好像它最接近用户一样。然后将元素的边框绘制在它们之上,并将背景颜色绘制在它们之下。

这转化为背景图像的声明(即使没有)将位于背景颜色之上。因此,如果您设置background而不是background-color,它将取代所有其他特定于属性的声明。

于 2013-10-17T21:18:13.717 回答