javascript - 检测浏览器在调整大小和更新元素位置时宽度变化了多少

标签 javascript html css

有一个 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 会保持在同一位置,因为它绝对定位在其相对容器中。

如何计算浏览器调整后的宽度并更新 followAlongDiv 的位置?

我将使用 window.addEventListener('resize', updatePosition),但我只是不知道如何处理 updatePosition 函数的公式。

最佳答案

首先,“followAlong-div”是一个类(在 className 之前需要“.”):

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/

希望对您有所帮助!

关于javascript - 检测浏览器在调整大小和更新元素位置时宽度变化了多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090434/

相关文章:

javascript - 在jquery中序列化两个复选框

html - CSS Transition : How can I make a div move, 暂停,然后用 1 transition 反转方向?

html - 将 Bootstrap 背景应用于面板页脚

javascript - 指令是有问题的 Bootstrap 导航-angularjs

javascript - 使用 if 语句调用函数

javascript - 创建打印链接

javascript - Node + Mysql - 连接问题

javascript - 如何在 <head> 中使用 getElementsByClassName 访问元素

javascript - 当在不同页面上单击链接时,试图让这个 wordpress 主题滚动到一个 id

html - 如何在html中创建一个视差网站(为什么我的背景图像不会覆盖整个屏幕?)