代码之家  ›  专栏  ›  技术社区  ›  anon

检测在调整元素大小和更新元素位置时浏览器宽度的变化程度

  •  0
  • anon  · 技术社区  · 8 年前

    有一个div元素绝对位于相对容器中。它最初位于四个按钮之一的下方。根据单击的按钮,我用JS计算按钮的x坐标,并将div元素移动到该按钮下方。这是我的标记和JS:

    <div id='container-of-four-buttons' style="width: 100%; position: relative;">
     <button>Foo</button>
     <button>Buzz</button>
     <button>Foo</button>
     <button>Buzz</button>
    </div>
    
    <div id='followAlong-container' style="width: 100%; position: relative;">
    <div class='followAlong-div' style="position:absolute; width: 15px; height: 13px;">Some stylized arrow</div>
    </div>
    
    var initialDiv = /* selected the second button to be initial */
    var followAlongDiv = document.querySelector('followAlong-div');
    var buttons = document.querySelectorAll('button');
    
    followAlongDiv.style.left = initialDiv + 89 + 'px';
    
    
    buttons.forEach(function(btn) {
      btn.addEventListener('click', function() {
        let xCoord = 0;
        xCoord += (div.offsetLeft - div.scrollLeft + div.clientLeft);
        followAlongDiv.style.left = xPos + 17 + 'px';
      });
    });
    

    如何计算浏览器已调整大小的宽度量并更新followAlongDiv的位置?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Elio García González    8 年前

    首先 跟随div “是一个类(需要在类名之前使用“.”):

    var followAlongDiv=document.querySelector('.followAlong div');

    xCoord+=(div.offsetLeft-div.scrollLeft+div.clientLeft);

    调整大小只是需要:

    window.onresize = ()=>{
              var xCoord = 0;
              xCoord += (selectedButton.offsetLeft);
              followAlongDiv.style.left = xCoord + 'px';
    
    }
    

    https://jsfiddle.net/vua4eLhc/