简体   繁体   English

使用jquery附加的样式元素

[英]Styling Elements that have been appended using jquery

I have div elements that are appended on a parent div. 我有附加在父div上的div元素。 Depending on the screen size, the div elements should resize but my efforts to do so using jquery .css() are failing all through. 根据屏幕大小,div元素应该调整大小,但是我使用jquery .css()所做的努力一直失败。 Kindly help. 请帮助。 Below is a sample of my code 以下是我的代码示例

var len = data.length; //a number comes here
var i;
for(i=1;i<len+1;i++){
    $(".app-body").append(
       "<div class='list-box' onclick='OpenHymn("+ i +")'>" +
       "<div class='circle-text'><div class='hym_num'>" + i + "</div></div>" +
       "</div>");
}
//calling the function that should resize the divs
GridBoxes();

function GridBoxes(){
    var width=window.innerWidth;
    var divisible=parseInt(width-40);
    var size=divisible/4;
    var boxes=$('.list-box');
    boxes.css("width",size+"px");
    boxes.css("height",size+"px");

} }

Put the function inside $(window).resize() for it to fire everytime the window is resized 将函数放在$(window).resize() ,以便在每次调整窗口大小时触发

Code: 码:

$(window).resize(function() {
  GridBoxes();
})

Example

You should really use media query's for this kind of problem. 您确实应该使用媒体查询来解决此类问题。

try this 尝试这个

 window.addEventListener("resize", GridBoxes);//called on window resize var len = 4; //changed to a number here for testing var i; for(i=1;i<len+1;i++){ $(".app-body").append( "<div class='list-box' onclick='OpenHymn("+ i +")'>" + "<div class='circle-text'><div class='hym_num'>" + i + "</div></div>" + "</div>"); } //calling the function that should resize the divs //GridBoxes(); function GridBoxes(){ var width=window.innerWidth; var divisible=parseInt(width-40); var size=divisible/4; var boxes=$('.list-box'); for(var b=0;b<boxes.length;b++){ boxes[b].css("width",size+"px"); boxes[b].css("height",size+"px"); } } 
 .list-box{border:1px solid red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="app-body"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM