通过Jquery改变Div的高度和宽度

Changing Height and Width of Div via Jquery

本文关键字:高度 Jquery 改变 Div 通过      更新时间:2023-09-26

我试图用方形盒子填充div容器。为什么这条线不行?我似乎不能改变我的div #gridSquare的高度和宽度。

$('#gridSquare').css({"height": "38.4", "width": "38.4"});

我将小提琴与我的其他代码连接起来。

感谢您的阅读!

小提琴

我最终想做的是使用squareSide变量来设置高度和宽度

你需要使用一个类而不是一个id (id应该是唯一的),然后你想要设置正方形的css 之后你已经添加到正方形:

var squareSide = 960 / 25;
console.log(squareSide);
for (var rows = 0; rows < 25; rows++) {
  $('<div class="gridSquare"></div>').appendTo('.container')
  for (var cols = 0; cols < 25; cols++) {
    $('<div class="gridSquare"></div>').appendTo('.container')
  }
}
$('.container').on('mouseenter', '.gridSquare', function() {
  $(this).css('background-color', 'white');
});
$('.gridSquare').css({
  "height": "38.4",
  "width": "38.4"
});
.container{
	background-color: grey;
	margin: 0 auto;
	text-align: center;
	font-size: 0;
	margin-bottom: 30px;
	width: 960px;
	height: 960px;
}
.gridSquare{
	background-color: black;
	display: inline-block;
	vertical-align: top;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

for循环也可以改成

// 625 = 25 * 25
for (var i = 0; i < 625; i++) {
    $('<div class="gridSquare"></div>').appendTo('.container')
}

可能

$('#gridSquare').css({"height": "38.4px", "width": "38.4px"});

class代替id

添加。

$(document).ready(function(){
    var squareSide = 960/25;

    console.log(squareSide);
    for(var rows = 0; rows < 25; rows++){
    $('<div class="gridSquare"></div>').appendTo('.container')
        for(var cols = 0; cols < 25; cols++){
            $('<div class="gridSquare"></div>').appendTo('.container');
            $('.gridSquare').css({"height": "38.4", "width": "38.4"});
        }
    }
    $('.container').on('mouseenter', '.gridSquare', function(){
        $(this).css('background-color', 'white');
    });
});
操纵http://jsfiddle.net/5ojjbwms/6/