获取文档滚动大小

时间:2018-01-26 10:52:05

标签: javascript html css

enter image description here

我正在使用键开发水平滚动,问题是如何计算文档滚动大小到中心所选元素:

我正在考虑:

  • 计算滚动宽度:dx
  • 计算窗口中间位置:wx
  • 计算元素宽度:ex

result = dx + wx - ex

并将结果应用于文档LEFT

d-x:0 <= 0文档X坐标 w-x:0&lt; = 0窗口X坐标

有些帮助计算文档滚动大小?

谢谢

PD:抱歉在图片中选择:P

1 个答案:

答案 0 :(得分:1)

一些计算距离的公式(使用left属性):

const distance = 2;

document.onkeydown = function(e){
    var div = document.getElementById('scroller');
    var style = div.style;
    var left = !isNaN(style.left) || style.left == '' ? 0 : parseInt(style.left.replace('px',''));
    
    if((e.key == 'ArrowRight') && (left - distance + div.offsetWidth >= window.innerWidth / 2)){
      left -= distance;
      document.getElementById('scroller').style.left = left + 'px';
    }else if((e.key == 'ArrowLeft') && (left + distance <= window.innerWidth / 2)){
      left += distance;
      document.getElementById('scroller').style.left = left + 'px';
    }
    
    calculateDistance();
}

function calculateDistance(){
  console.clear();
  var text = "middle: " +  (window.innerWidth / 2) + "px";
  
  var parentDivLeft = document.getElementById("scroller").offsetLeft;
  
  var elements = document.getElementsByClassName("element");
  
  for(let element of elements){
    let middleElementDistance = parentDivLeft + element.offsetLeft + (element.offsetWidth / 2);
    text += "\nelement " + element.innerHTML + ": " + middleElementDistance + "px(middle), distance of " + Math.abs(middleElementDistance - window.innerWidth / 2) + "px.";
  }
  
  console.log(text);
}

function clickElement(){
  this.style.background = 'red';
}

for(let div of document.getElementsByClassName('element')){
  div.onmouseup = mouseUpOver;
  div.onmousedown = click;
  div.onmouseover = mouseUpOver;
  div.onmouseout = mouseOut;
}

function click(){
  this.style.background = '#0A0';
  
  let parentDiv = document.getElementById("scroller");
  
  let middleElementDistance = parentDiv.offsetLeft + this.offsetLeft + (this.offsetWidth / 2);
  let distance = window.innerWidth / 2 - middleElementDistance;
  
  parentDiv.style.left = (parentDiv.offsetLeft + distance) + 'px';
  calculateDistance();
}

function mouseUpOver(){
  this.style.background = '#0C0';
}

function mouseOut(){
  this.style.background = '#FFF';
}
body{
  margin: 0;
  padding: 0;
}

#middleBar{
  position: absolute;
  width: 50%;
  height: 100%;
  border-right: solid 1px red
}

#scroller{
  position: absolute;
  width: 200%;
  border: 1px solid black;
  padding: 10px;
  left: 0;
}

.element{
  cursor: pointer;
  position: relative;
  display: inline-block;
  width: 200px;
  text-align: center;
  border: 1px solid green;
}

body {
    overflow:hidden;
}
<div id="middleBar"></div>

<div id="scroller">
  <div class="element">1</div>
  <div class="element">2</div>
  <div class="element">3</div>
  <div class="element">4</div>
  <div class="element">5</div>
</div>