Создать квадрат, привязанный к прямоугольнику с изменяемым размером - PullRequest
0 голосов
/ 25 февраля 2019

У меня есть прямоугольник на моей странице, который должен быть заполнен квадратом в центре.Этот прямоугольник может быть как горизонтальным, так и вертикальным.Это означает, что множество существующих вопросов, основанных на создании квадрата из ширины вмещающей рамки, не работают. [1] [2]

Этот квадрат также может динамически меняться, и этот подход не изменяет размер квадрата.Я также хотел бы не использовать JavaScript или JQuery, если это возможно.Это единственное, для чего я бы использовал JQuery.

Ниже вы можете увидеть, что код должен делать в начале, но когда вы изменяете размер окна, он не меняет размер квадрата.

/* based on https://stackoverflow.com/a/5445536*/
$('.body').resizable();
var containingBlock = $('.box-rect');
var cmin = Math.min(containingBlock.width(), containingBlock.height());

$('#box-square').css({
  'height': cmin+'px',
  'width': cmin+'px'
});
.body{
  width: 200px;
  height: 100px;
}

.box-rect {
  width: 100%;
  height: 100%;
  min-width: 50px;
  min-height: 50px;
  
  display: flex;
  justify-content: center;
  align-items: center;
  
  /* example bounding box */
  border: 1px solid gray;
}

.box-square {
  width: 50px; /* min(box-rect.height, box-rect.width) */
  height: 50px; /* box-rect min */
}

/*
The following is using a mix between the following two answers:
https://stackoverflow.com/a/6615994
https://stackoverflow.com/a/20117454
*/
.box-reset {
  position: relative;
  height: 100%;
  width: 100%;
}

.box-reset:before {
  content: "";
  display: block;
  padding-top: 100%;
}

.box {
  position:  absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;

  /* example gray box */
  height: 100%;
  background-color: gray;
}
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class='body'>
  <div class="box-rect">
    <div class="box-square">
      <div class="box-reset">
        <div class="box">
          Not working at all
        </div>
      </div>
    </div>
  </div>
</div>
<br />
<div class='body'>
  <div class="box-rect">
    <div class="box-square" id="box-square">
      <div class="box-reset">
        <div class="box">
          Fills to the bounds of the rectangle on load.
        </div>
      </div>
    </div>
  </div>
</div>

Для полной ясности:

  • Первый приведенный выше пример совсем не изменяет размер серого квадрата.
  • Второй пример изменяет размер серого квадрата до границы прямоугольника.(Что я хочу)

    Однако при изменении размера содержащего блока он не изменяет размер серого квадрата до границы прямоугольника.

Я хочу изменить размерквадрат к границе прямоугольника.Как и во втором примере, когда я изменяю размер содержащего блока.

Я бы предпочел сделать все это в чистом CSS .

Ответы [ 2 ]

0 голосов
/ 25 февраля 2019

Вы можете посмотреть пример jQuery .Лучше понять, как это работает.Я сделал похожий пример на jsfiddle .

* {
    margin: 0;
    padding: 0;
    box-sizing:border-box;
  }
  #resizable { 
    display:flex;
    justify-content:center;
    align-items:center;
    width: 150px; 
    height: 150px; 
    min-width:100px;
    min-height:100px;
  }

  #resizable h3 {
    display:flex;
    justify-content:center;
    align-items:center;
    height: 100px;
    width: 100px;
    text-align:center;
  }
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Resizable - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#resizable" ).resizable();
  } );
  </script>
</head>
<body>
<div id="resizable" class="ui-widget-content center-center">
  <h3 class="ui-widget-header">Resizable</h3>
</div>
</body>
</html>

<!-- Reference link https://jqueryui.com/resizable/ -->
0 голосов
/ 25 февраля 2019

Убрал статическую высоту и ширину, которая применялась из js, и добавил width: 50%; и height: 50%; к .box-square

$('.box-rect').resizable();
.body{
  width: 400px;
  height: 200px;
}

.box-rect {
  width: 100%;
  height: 100%;
  min-width: 100px;
  min-height: 100px;
 
  display: flex;
  justify-content: center;
  align-items: center;
  
  /* example bounding box */
  border: 1px solid gray;
}

.box-square {
    width: 100px;
    height: 100px;
 /* width: 100px;  min(box-rect.height, box-rect.width) */
 /* height: 100px;  box-rect min */
}

/*
The following is using a mix between the following two answers:
https://stackoverflow.com/a/6615994
https://stackoverflow.com/a/20117454
*/
.box-reset {
  position: relative;
  height: 100%;
  width: 100%;
}


.box {
    height: 100%;
    background-color: gray;
}
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class='body'>
  <div class="box-rect">
    <div class="box-square">
      <div class="box-reset">
        <div class="box">
        </div>
      </div>
    </div>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...