首页 > 解决方案 > 动态填充两个对象之间的空间

问题描述

填充这两个对象之间的空间的最佳方法是什么,本质上是制作一个对象来填充从 a 到 b 的最右边的空间。我需要一个动态的解决方案,因为 A 和 B 的位置会有所不同,有时 B 会比 A 更左。我希望它们从两个单独的对象开始。还要注意我只希望填充两者之间的空间,外面什么都没有。

function myFunction() {
  var x = document.getElementById('a');
  var y = document.getElementById('b');

  x.style.right = "70%";
  y.style.right = "50%";

  var greenRect = x.getBoundingClientRect();
  var blueRect = y.getBoundingClientRect();

}
h1 {
  position: relative;
  width: auto;
  height: 50px;
  background-color: beige;
}

h2 {
  position: relative;
}

#a {
  position: relative;
  width: 50px;
  height: 50px;
  background-color: green;
  float: right;
  margin-left: -50px;
  transform-origin: left;
  border-radius: 50%;
}

#b {
  position: relative;
  width: 50px;
  height: 50px;
  background-color: green;
  float: right;
  border-radius: 50%;
}
<h1>
  <div id='a'></div>
  <div id='b'></div>
</h1>


<h2>


  <button onclick='myFunction()'>PRESS</button>


</h2>

标签: javascripthtmlcsspositionwidth

解决方案


您可以使用一些背景和框阴影技巧在视觉上填充以下之间的空间:

var x = document.getElementById('a');
  var y = document.getElementById('b');

function myFunction() {

  var r = Math.random()*100;
  y.style.right=r+"%";
  x.style.right=(Math.random()*(100 - r) + r)+"%";

}
h1 {
  overflow:auto;
  background-color: blue;
  color:#fff;
  text-align:center;
}

#a {
  position: relative;
  width: 50px;
  height: 50px;
  background-color: green;
  float: right;
  margin-left: -50px;
  transform-origin: left;
  border-radius: 50%;
  box-shadow:-50vw 0 0 50vw beige;
}

#b {
  position: relative;
  width: 50px;
  height: 50px;
  background-color: green;
  float: right;
  border-radius: 50%;
  box-shadow:50vw 0 0 50vw beige;
}
<h1>
  <div id='a'>1</div>
  <div id='b'>2</div>
</h1>


<h2>


  <button onclick='myFunction()'>PRESS</button>


</h2>


推荐阅读