jQuery-通过定位元素类型查找元素之间的空间

时间:2018-08-03 06:01:42

标签: jquery

我需要找出每个元素之间的空间。让我们在X和Y,Y和Z与...之间留出空格。

通过使用以下代码,我可以通过使用其ID或类来获得相同的结果

<a href="#" id="x">X</a>
<a href="#" id="y" style="margin-left:100px;">Y</a>
<div class="distance">Total distance</div>

distX = y.offsetLeft - x.offsetLeft;
distY = y.offsetTop - x.offsetTop;
distance = Math.sqrt(distX*distX + distY*distY);
jQuery('.distance').html('Distance: ' + Math.floor(distance) + 'px');

我得到的输出为:Distance: 116px,这是正确的。

小提琴http://jsfiddle.net/xe1328nv/1/

感谢@vladkras提供第一个解决方案Measure distance between two HTML elements' centers

但是对于我来说,定位标记是动态出现的,因此我无法分配类ID。

在以下情况下,如何找出每个元素之间的间隔?

<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<a href="#">Link 4</a>
<a href="#">Link 5</a>

输出应该如下:

Space between Link 1 & Link 2 = ???
Space between Link 2 & Link 3 = ???
Space between Link 3 & Link 4 = ???
Space between Link 4 & Link 5 = ???

http://jsfiddle.net/dr4kqxzc/

3 个答案:

答案 0 :(得分:1)

在代码中已注释。让我知道是否有任何问题。

$('.social-links a').each(function() {
  //alert($(this).attr('href'));
  var popupText = $(this).attr('data-social');
  $(this).append('<div class="popup-text">' + popupText + '</div>');
});

// get the NodeList of links
const links = document.querySelectorAll('.social-links a');

// define the variables we need
let distance;
let distanceHtml = '';
let distX;
let distY;

// iterate over the NodeList
for (let i = 0; i < links.length - 1; i++) {
  distX = links[i + 1].offsetLeft - links[i].offsetLeft;
  distY = links[i + 1].offsetTop - links[i].offsetTop;
  distance = Math.sqrt(distX * distX + distY * distY);
  // using a template literal here (ES6)
  distanceHtml += `Space between Link ${i+1} &amp; Link ${i+2} = ${Math.floor(distance)}px<br />`;
}

document.getElementById('distance').innerHTML = distanceHtml;
body {
  margin: 50px auto;
}

.main-div {
  width: 600px;
  margin: auto;
  border: 1px solid #ccc;
  font-family: verdana;
  font-size: 13px;
  padding: 120px 20px 10px 20px;
  background: #f5f5f5;
}

.main-div a {
  display: inline-block;
  position: relative;
}

.main-div a .popup-text {
  display: inline-block;
  position: absolute;
  top: -22px;
  left: 0;
  background: #ccc;
  padding: 2px 5px;
  border: 1px solid #ffffff;
}

.popup-text:before {
  content: "";
  display: block;
  background: red;
  width: 1px;
  height: 20px;
  float: left;
  margin: 0;
  position: absolute;
  left: 0px;
  top: 0px;
  height: 34px;
}

#distance {
  background-color: #f0f0f0;
  border: 1px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-div">
  <div class="social-links">
    <a href="javascript:;" data-social="Facebook"><img src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/facebook_circle_color-20.png" alt="Facebook" /></a>
    <a href="javascript:;" data-social="Twitter"><img src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/twitter_circle_color-20.png" alt="Twitter" /></a>
    <a href="javascript:;" data-social="Youtube"><img src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/youtube_circle_color-20.png" alt="Youtube" /></a>
    <a href="javascript:;" data-social="Linkedin"><img src="https://cdn3.iconfinder.com/data/icons/free-social-icons/67/linkedin_circle_color-20.png" alt="Linkedin" /></a>
  </div>
</div>
<div id="distance"></div>

我没有使用jQuery(除了我从提琴中复制的部分),因为在这里没有必要使用jQuery(对于大多数事情而言)。我更喜欢将香草Javascript用于几乎所有内容。

答案 1 :(得分:1)

您已经有了创建通用函数的代码...

您要做的就是在每个元素内进行迭代,并检查是否有下一个要比较的元素。

function spaceBetween(x,y,namex="x",namey="y"){
  distX = y.offsetLeft - x.offsetLeft;
  distY = y.offsetTop - x.offsetTop;
  distance = Math.sqrt(distX*distX + distY*distY);
  $('.distance').append('Distance ('+namex+' - '+namey+'): ' + Math.floor(distance) + 'px <br>');
}

var x = $('#x')[0];
var y = $('#y')[0];

spaceBetween(x,y)

 $(".random-elements a").each(function(i){
  if($(this).next()[0] !== undefined){
    var x = $(this);
    var y = $(this).next();
    spaceBetween(x[0],y[0],x.html(),y.html())
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="x">X</a>
<a href="#" id="y" style="margin-left:100px;">Y</a>

<div class="random-elements">
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>

<div class="distance"></div>

答案 2 :(得分:1)

document.addEventListener('DOMContentLoaded', () => {
  const elements = document.querySelectorAll('.wrapper__link');
  const offsets = [...elements].map((elem, indx, arr) => {
    const elemMarginLeft = window.getComputedStyle(elem).marginLeft.match(/[0-9]+/g)[0];
    const elemUnit = window.getComputedStyle(elem).marginLeft.match(/[^0-9]+/g)[0];
    const elemOffset = indx === 0 ? 0 : elemMarginLeft * indx;

    return indx === 0 ? `` : `Space between ${arr[indx - 1].text} & ${elem.text} = ${elemOffset}${elemUnit}`;
  }).join('<br/>');

  document.querySelector('.result').innerHTML = offsets
});
.wrapper { background-color:cornflowerblue; padding: 15px; }
.wrapper__link { background-color: aqua; padding:5px; margin-left: 15px; }
.wrapper__link--margin-left-50 { margin-left: 50px } 
.wrapper__link--margin-left-100 { margin-left: 100px } 

.result { margin-top: 10px }
<div class="wrapper">
  <a class="wrapper__link" href="#">Link 1</a>
  <a class="wrapper__link" href="#">Link 2</a>
  <a class="wrapper__link wrapper__link--margin-left-50" href="#">Link 3</a>
  <a class="wrapper__link" href="#">Link 4</a>
  <a class="wrapper__link wrapper__link--margin-left-100" href="#">Link 5</a>
</div>
<div class="result"></div>