javascript – Div超过其父元素

前端之家收集整理的这篇文章主要介绍了javascript – Div超过其父元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > Why do child divs extend beyond their parent div?                                    1个
我正在尝试创建自定义滚动条,我正在使用translate3d滚动.唯一的问题是,当你一直滚动到底部时,拇指(卷轴)走得太远了.我正在使用公认的公式,但由于某种原因,它超过了它的父包装器.这是公式:

scrollPosition * scrollBarThumb_height / content_height

我做错了什么,如何让拇指完全留在父母视野中?

JSFiddle

console.clear();

var innerWrapper = document.getElementById('innerWrapper');
var scrollBar = document.getElementById('scrollbar');
var scrollBarThumb = scrollBar.firstElementChild

scrollBarThumb.style.height = (innerWrapper.offsetHeight * innerWrapper.offsetHeight / innerWrapper.scrollHeight) + 'px';

innerWrapper.addEventListener('mousewheel',handleScroll);
innerWrapper.addEventListener('DOMMouseScroll',handleScroll);

innerWrapper.style.transform = 'translate3d(0px,0px,0px)';

function handleScroll(e) {
  // Prevent parents from scrolling
  e.preventDefault();
  var direction = (e.detail < 0 || e.wheelDelta > 0) ? 1 : -1; // 1 = scroll down,-1 = scroll

  var start = parseInt(innerWrapper.style.transform.split(',')[1],10);
  var scrollPosition = start + direction * 100; // Cannot use `deltaY`,because not all browsers support it.
  var scrolledToBottom = innerWrapper.scrollHeight - innerWrapper.parentElement.offsetHeight;
  scrollPosition = clamp(scrollPosition,-scrolledToBottom,0);

  innerWrapper.style.transform = 'translate3d(0px,' + scrollPosition + 'px,0px)';
  scrollBarThumb.style.top = -(scrollPosition * scrollBarThumb.offsetHeight / innerWrapper.parentElement.offsetHeight) + 'px'
}

function clamp(val,min,max) {
  if (typeof min !== 'number') min = 0;
  if (typeof max !== 'number') max = 1;
  return Math.min(Math.max(val,min),max);
}
#outerWrapper {
  height: 400px;
  overflow: hidden;
  display: flex;
}
#content {
  background-image: url("http://images.freeimages.com/images/premium/previews/3037/30376024-beautiful-flower-portrait.jpg");
  width: 400px;
}
#scrollbar {
  height: 100%;
  width: 50px;
  background-color: orange;
}
#scrollbar_thumb {
  background-color: yellow;
  border: 2px solid blue;
  position: relative;
}
最佳答案
边框未正确计算到总元素的高度,从而产生问题.

只需添加Box-sizing:border-Box;解决问题:

#scrollbar_thumb {
    ...
    Box-sizing: border-Box;
}

工作JSFiddle fork:https://jsfiddle.net/azizn/9nfns6kk/

原文链接:/css/426974.html

猜你在找的CSS相关文章