简体   繁体   English

动态增加div宽度和高度

[英]Increasing div width and height dynamically

On my webpage there are Gridster widgets which have multiple images in them. 在我的网页上有Gridster小部件,其中包含多个图像。 Images can be added with + button.The widgets can be resized as well. 可以使用+按钮添加图像。小部件也可以调整大小。

I am displaying these images inside div with class=imagewrap and the images have class images with them. 我在div中使用class=imagewrap显示这些图像,图像中包含类images

My overall aim 我的总体目标

I want to increase/decrease the div width and height dynamically as the widget is resized.Also I want the aspect ration of the image to be preserved. 我想在调整窗口小部件时动态地增加/减少div的宽度和高度。我也希望保留图像的宽高比。

What I have achieved/tried so far 到目前为止我所取得的成就/尝试

I currently have declared the div width and height as 80px and I am able to fit all the images perfectly in them maintaining its aspect ratio. 我目前已经宣布div widthheight80px ,我能够完美地将所有图像完美地保持在它们中,保持其纵横比。

Fiddle 小提琴

 .imagewrap { display:inline-block; position:relative; width: 80px; height: 80px; margin-top: 1px; margin-right: 1px; margin-left: 1px; margin-bottom: 1px; } .images { max-width:100%; max-height:100%; } 
  <div class="imagewrap"><img class="images" src='+ images[j] +' title="' + titles[j]+ '"><input type="button" class="removediv" value="X" /></div></div> 

I would instead use the image as a background, and use background-size:cover; 我会改为使用图像作为背景,并使用background-size:cover; to keep the photo proportioned as much as possible. 保持照片尽可能的比例。 This way you could specify the width and height of the image div in percentages, and the photo inside would scale. 这样,您可以指定图像div的宽度和高度百分比,并且内部的照片可以缩放。 You could background-position:center; 你可以background-position:center; it so that way if the frame gets too tall or wide, only a slight portion of the edges will get cut off. 这样,如果框架太高或太宽,只有一小部分边缘会被切断。

So for your image-wrap div, give it the proper size that you want and apply the background to it. 因此,对于您的图像包装div,请为其提供所需的适当大小并将背景应用于它。 You can use '+ images[j] +' as well on the div, by making it an inline style that's applied. 您可以在div上使用'+ images[j] +' ,使其成为应用的内联样式。 So: <div style="background-image=url('+images[j]+');"> 所以: <div style="background-image=url('+images[j]+');">

 .imagewrap { display:inline-block; position:relative; width: 80px; height: 80px; margin-top: 1px; margin-right: 1px; margin-left: 1px; margin-bottom: 1px; background-image:url(http://www.placecage.com/200/300); background-size:cover; background-position:center; } .images { max-width:100%; max-height:100%; } 
  <div class="imagewrap"><input type="button" class="removediv" value="X" /></div></div> 

Added Flex CSS to flex the content. 添加Flex CSS以弯曲内容。 then added min-width and height. 然后添加最小宽度和高度。 then added 'img-responsive' class to <img class='images'> using JQuery addClass() . 然后使用JQuery addClass()'img-responsive'类添加到<img class='images'> let me know if this does it for you 让我知道这是否适合你

UPDATED: 更新:

 var gridster; //Initializing Gridster gridster = $(".gridster ul").gridster({ widget_base_dimensions: [100, 100], widget_margins: [5, 5], helper: 'clone', serialize_params: function($w, wgd) { return { images: $w.find('.imagenames').val().trim(), title: $w.find('.hoverinformation').val().trim(), col: wgd.col, row: wgd.row, size_x: wgd.size_x, size_y: wgd.size_y } }, resize: { enabled: true } }).data('gridster'); //JSON which I get from backend var json = [{ "images": "https://png.icons8.com/metro/2x/boy.png,https://png.icons8.com/metro/2x/boy.png,https://png.icons8.com/metro/2x/chapel.png", "title": "AB,DE,EF", "infoonwidgets": "Some Info", "col": 1, "row": 1, "size_y": 2, "size_x": 2 } ]; //Loop which runs over JSON to generate <li> elements in HTML for (var index = 0; index < json.length; index++) { var images = json[index].images.split(','); var titles = json[index].title.split(','); var imageOutput = ""; for (var j = 0; j < images.length; j++) { imageOutput += '<div class="imagewrap"><img class="images" src=' + images[j] + ' title="' + titles[j] + '"> <input type="button" class="removediv" value="X" /></div></div>'; } gridster.add_widget('<li class="new" ><button class="addmorebrands" style="float: left;">+</button><button class="delete-widget-button" style="float: right;">-</button><textarea class="info-on-widgets">' + json[index].infoonwidgets + '</textarea><div class="content"><div class="row">' + imageOutput + '</div></div><textarea class="imagenames">' + json[index].images + '</textarea><textarea class="hoverinformation">' + json[index].title + '</textarea></li>', json[index].size_x, json[index].size_y, json[index].col, json[index].row); } function trimChar(string, charToRemove) { while (string.charAt(0) == charToRemove) { string = string.substring(1); } while (string.charAt(string.length - 1) == charToRemove) { string = string.substring(0, string.length - 1); } return string; } function updateTextarea(imageNames, imageSrc) { var imageNamesValue = imageNames.val(); imageNamesValue = imageNamesValue.replace(imageSrc, ''); imageNamesValue = trimChar(imageNamesValue, ','); imageNamesValue = imageNamesValue.trim(); imageNames.val(imageNamesValue.replace(/,,/g, ",")); } //Function to delete an image from widget $(document).on('click', '.removediv', function() { var imageDelete = $(this).closest('div.imagewrap'); var imgTag = imageDelete.find('img'); var imageTitle = imgTag.attr('title'); var imageSrc = imgTag.attr('src'); var textareaName = $(this).closest('li').find('.imagenames'); var textareaTitle = $(this).closest('li').find('.hoverinformation'); updateTextarea(textareaName, imageSrc); updateTextarea(textareaTitle, imageTitle); //Here I want that will remove the content from both the textareas imageDelete.remove(); }); //Function to delete a widget $(document).on("click", ".delete-widget-button", function() { var gridster = $(".gridster ul").gridster().data('gridster'); gridster.remove_widget($(this).parent()); }); //Adding Images from Modal var parentLI; var selectedImageSRC = ""; $(document).on("click", ".addmorebrands", function() { parentLI = $(this).closest('li'); $('#exampleModalCenter').modal('show'); }); $('#exampleModalCenter img').click(function() { parentdiv = $(this).closest('div.outerdiv'); if (parentdiv.hasClass('preselect')) { parentdiv.removeClass('preselect'); selectedImageSRC = selectedImageSRC.replace($(this).attr('src'), ""); selectedImageSRC = trimChar(selectedImageSRC, ','); selectedImageSRC = (selectedImageSRC.replace(/,,/g, ",")); console.log("In remove"); console.log(selectedImageSRC); console.log("Parent Div in remove"); console.log(parentdiv); } else { parentdiv.addClass('preselect'); if (selectedImageSRC === '') { selectedImageSRC += $(this).attr('src'); } else { selectedImageSRC += ',' + $(this).attr('src'); } console.log("In add"); console.log(selectedImageSRC); console.log("Parent Div in Add"); console.log(parentdiv); } }); $('#add-image').click(function() { console.log("In add image"); console.log(selectedImageSRC); var multipleImageSRC = ""; multipleImageSRC = selectedImageSRC.split(','); console.log("Splitted Images"); console.log(multipleImageSRC); var multipleImages = ""; for (var j = 0; j < multipleImageSRC.length; j++) { multipleImages += '<div class="imagewrap"><img class="images" src="' + multipleImageSRC[j] + '" title="Manual Addition"> <input type="button" class="removediv" value="X" /></div>' console.log("Multiple Images SRC"); console.log(multipleImages); } parentLI.append(multipleImages); var imageNameValue = parentLI.children('.imagenames').val(); var imageTitleValue = parentLI.children('.hoverinformation').val(); //Loop for Updating Textarea with ImageNames var imageNameInTextarea = ""; for (var j = 0; j < multipleImageSRC.length; j++) { imageNameInTextarea += multipleImageSRC[j].replace("/static/images/brands/", "") + ","; } //To remove last ',' after the names imageNameInTextarea = trimChar(imageNameInTextarea, ','); console.log(imageNameInTextarea); //Loop calculating lenght of number of images added and correspondingly putting "Manual Addition" manualAddition = ""; for (var j = 0; j < multipleImageSRC.length; j++) { manualAddition += "Manual Addition" + ","; } //To remove last ',' after the names manualAddition = trimChar(manualAddition, ','); console.log("Manual Textarea"); console.log(manualAddition); if (imageNameValue === '') { parentLI.children('.imagenames').val(imageNameInTextarea); } else { parentLI.children('.imagenames').val(imageNameValue + ',' + imageNameInTextarea); } if (imageTitleValue === '') { parentLI.children('.hoverinformation').val(manualAddition); } else { parentLI.children('.hoverinformation').val(imageTitleValue + ',' + manualAddition); } $('#exampleModalCenter').modal('hide'); removeclasses() }); function removeclasses() { //Removing preselect class from all the div's when close button or add brand button is clicked. a = $('div .outerdiv').removeClass('preselect'); selectedImageSRC = ""; console.log(a); } $('document').ready(function() { $('img[class*="images"]').addClass('img-responsive'); }); 
 .info-on-widgets { width: 90%; } .removediv { position: absolute; right: 1%; top: 1%; } .preselect { background: lightgreen } .modal-body { width: 100%; position: relative; text-align: center; } .outerdiv { height: 30%; width: 30%; display: inline-block; } .imagenames, .hoverinformation, .widget-color { display: none; } /* CSS for increasing image aspect ratio when resized */ .content {} .row { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-orient: horizontal; -moz-box-orient: horizontal; box-orient: horizontal; flex-direction: row; -webkit-box-pack: center; -moz-box-pack: center; box-pack: center; justify-content: center; -webkit-box-align: center; -moz-box-align: center; box-align: center; align-items: center; } .imagewrap { -webkit-box-flex: 1; -moz-box-flex: 1; box-flex: 1; -webkit-flex: 1 1 auto; flex: 1 1 auto; padding: 2%; margin: 1%; text-align: center; } .images { max-width: 100%; margin: 0px auto; text-align: center; min-width: 100%; height: auto; } 
 <link href="https://dsmorse.github.io/gridster.js/demos/assets/css/demo.css" rel="stylesheet"/> <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.gridster/0.5.6/jquery.gridster.css" rel="stylesheet"/> <div class="gridster"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.gridster/0.5.6/jquery.gridster.min.js"></script> <!-- <li> from JSON are placed here --> <ul> </ul> </div> <!-- Declaration of Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Add Icons</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="removeclasses()"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!-- Images which I retrieve from backend for now they are hardcoded paths and actually are dynamic(No fixed number)--> <div class="outerdiv"><img src="https://cdnd.icons8.com/wp-content/uploads/2015/07/Run-Command-100.png"></div> <div class="outerdiv"><img src="https://png.icons8.com/metro/2x/chapel.png"></div> <div class="outerdiv"><img src="https://png.icons8.com/metro/2x/boy.png"></div> <div class="outerdiv"><img src="https://png.icons8.com/metro/2x/wacom-tablet.png"></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="removeclasses()">Close</button> <button id="add-image" type="button" class="btn btn-primary">Add Image</button> </div> </div> </div> </div> 

Read more about Flex CSS (AKA: Flexbox CSS) at: Typical use cases of Flexbox (https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox) 在以下位置阅读有关Flex CSS(AKA:Flexbox CSS)的更多信息:Flexbox的典型用例(https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox)

width and height in percent commands, maybe you combine this with a javascript, who gives you per tick or other event the values back in the css 宽度和高度百分比命令,也许你把它与一个javascript结合起来,你给每个tick或其他事件返回css中的值

(without proof) (没有证据)

window.onresize = function () {

    var xx = document.getElementById('imagewrap').offsetWidth;  // i think it is a html-dom-id
    var yy = document.getElementById('imagewrap').offsetHeight;  // i think it is a html-dom-id  

    var x = 10;
    var y = 10;

    var xx = xx + x;
    var yy = yy + y;

    document.getElementById('imagewrap').offsetWidth = xx;
    document.getElementById('imagewrap').offsetHeight = yy;

   }

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

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