将getBoundingClientRect值赋予元素

时间:2018-09-03 09:30:34

标签: javascript css arrays foreach

我正在尝试在span元素上复制视频和img(x,y,height,weidth)的css值。为此,我使用了getBoundingClientRect,但是它只复制了我的video / imgs元素的第一个元素的值。

var projectEA = document.getElementById("project-ea");
var medias = projectEA.querySelectorAll("video, img");
console.log(medias);

medias.forEach(function(media){

  var getObj = media.getBoundingClientRect();
  console.log(getObj);
  var legends = projectEA.getElementsByClassName("item__legend");
  var legendsArray = [].slice.call(legends);
  
  legendsArray.forEach(function(legend){
      legend.style.top = (getObj.top + getObj.height) + 'px';
      legend.style.left = getObj.left + 'px';
      legend.style.width = getObj.width + 'px';
      legend.style.height = getObj.height + 'px';
  });
  
});
<section id="project-ea" class="project">

    <span class="item__legend">EA13 - Version mobile</span>
    <span class="item__legend">EA13 - Version desktop</span>
    <span class="item__legend">EA13 - Texture</span>
    <span class="item__legend">EA12 - Texture</span>
    <span class="item__legend">EA12 - Version desktop</span>

    <div class="project__video">
      <video width="100%" class="video-js" preload="auto" autoplay loop muted>
          <source
          src="ea-mobile.mp4"
          type="video/mp4">
      </video>
    </div>
    <div class="project__video">
      <video width="100%" class="video-js" preload="auto" autoplay loop muted>
          <source
          src="ea13.mp4"
          type="video/mp4">
      </video>
    </div>
    <div class="project__photo">
      <img src="ea-photo1.jpg" class="half-img-left" alt="Electro Alternativ Texture"/>
      <img src="ea-photo2.jpg" class="half-img-right" alt="Electro Alternativ Texture"/>
    </div>
    <div class="project__video">
      <video width="100%" class="video-js" preload="auto" autoplay loop muted>
          <source
          src="electroalternativ.mp4"
          type="video/mp4">
      </video>
    </div>

</section>

我希望第一个span元素获取第一个媒体值,第二个span元素获取第二个媒体值,等等。

0 个答案:

没有答案