javascript - 动态增加div的宽度和高度

标签 javascript jquery html css

在我的网页上有Gridster其中包含多个图像的小部件。可以使用 + 按钮添加图像。小部件也可以调整大小。

我在带有 class=imagewrap 的 div 中显示这些图像,并且这些图像具有 images 类。

我的总体目标

我想在调整小部件大小时动态地增加/减少 div 宽度和高度。我还希望保留图像的宽高比。

到目前为止我已经取得/尝试过什么

我目前已将 div widthheight 声明为 80px 并且我能够将所有图像完美地放入其中并保持其外观比率。

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>

最佳答案

添加了 Flex CSS 来调整内容。然后添加最小宽度和高度。然后添加'img-responsive'类别为 <img class='images'>使用 JQuery addClass() .让我知道这是否适合你

更新:

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>

阅读更多关于 Flex CSS(又名:Flexbox CSS)的信息:Typical use cases of Flexbox (https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox)

关于javascript - 动态增加div的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49637948/

相关文章:

javascript - 注释中的 Vue.js 绑定(bind)

javascript - 使用 JavaScript 链接放大标记

javascript - jQuery UI Datepicker 未安装

javascript - 如何用不同的颜色显示数组

javascript - 如何在运行时创建多个切换?

javascript - IE 输入文件属性未定义

javascript - 在 DateRangePicker 中将日期格式转换为 'YYYY-MM-DD'

javascript - jquery 滚动在我的网站上不起作用

html - 背景图像不显示在 html css 中

html - CSS 背景图像与左下角对齐而不强制滚动条