简体   繁体   English

在窗口调整大小时保持内容位置?

[英]Keep content position on window resize?

For reprodution set scroll thumb to end of scrollbar and change window size: https://jsfiddle.net/coryphoenixxx/zLq3u4sn/36/为了重现设置滚动拇指到滚动条的末尾并更改窗口大小: https ://jsfiddle.net/coryphoenixxx/zLq3u4sn/36/

How to stop this and keep sizes of inner box in vw?如何阻止这种情况并在大众中保持内盒的尺寸?

<html>
<body>
<div class='box'>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
  <div class='inner-box'></div>
</div>
</body>
</html>
.box {
  width: 30vw;
  height: 12vw;
  border: 0.1vw solid black;
  
  display: flex;
  flex-direction: row;
  overflow-x: scroll;
  overflow-y: hidden;
}

.inner-box {
  margin: 1vw;
  min-width: 7vw;
  height: 7vw;
  border: 0.1vw solid black;
}

Ok, I found solution好的,我找到了解决方案

const box = document.querySelector('.box');

let boxScrollPct = 0;
let ignoreScroll = false;
box.addEventListener('scroll', ({ target: t }) => {
  if (ignoreScroll) return;
  boxScrollPct = t.scrollLeft / (t.scrollWidth - t.clientWidth);
});

let timeOutId = null;

window.addEventListener('resize', e => {
  ignoreScroll = true;
  box.scrollLeft = boxScrollPct * (box.scrollWidth - box.clientWidth);
  
  clearTimeout(timeOutId);
  timeOutId = setTimeout(() => {
    ignoreScroll = false;
  }, 50);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM