【问题标题】:How to achieve negative scrolling in Javascript/Typescript?如何在 Javascript/Typescript 中实现负滚动?
【发布时间】:2020-10-13 04:53:22
【问题描述】:

我有一个可以用鼠标指针拖动到的 div 元素。当我触摸或越过右侧或底部边界时,它会自动显示滚动条。但是,当我通过顶部或左侧边界触摸或穿过 div 元素时,没有滚动条。

如果我的 div 越过这些边界(顶部和左侧),是否也可以获得左侧和顶部的滚动条?

这是我为拖动所做的代码:

<!DOCTYPE html>
<html>
<style>
#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #d3d3d3;
 
}

#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
</style>
<body>

<h1>Draggable DIV Element</h1>

<p>Click and hold the mouse button down while moving the DIV element</p>

<div id="mydiv">
  <div id="mydivheader">Click here to move</div>
  <p>Move</p>
  <p>this</p>
  <p>DIV</p>
</div>

<script>
//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
</script>

</body>
</html>

【问题讨论】:

    标签: javascript html css typescript


    【解决方案1】:

    据我所知,您不能这样做,因为浏览器不允许负滚动。

    但是,您可以做的是重新计算所有其他元素的位置并滚动文档,以便创建添加负滚动的错觉。如果你将一个元素从 10px 移动到 -20px 左边,你现在必须把它放在 0 上,然后将 30 添加到每个其他元素。然后,您可以使用 window.scrollTo() 函数将可见区域向右移动 30 个像素。只要确保在拖动端进行重新计算即可。您不想每次在屏幕上拖动项目时都重新计算它。

    【讨论】:

      猜你喜欢
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多