如何通过拖动而不是使用滚动条来滚动div [英] How to scroll through a div by dragging and not by using the scroll bars

查看:321
本文介绍了如何通过拖动而不是使用滚动条来滚动div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个使用触摸屏界面的项目。我在较小的div内有一个div,因此较小的div具有滚动条以访问第一个div的其余部分。这是它的基本代码。

I am working on a project that uses a touch-screen interface. I have a div inside of a smaller div, so the smaller div has scroll bars to access the rest of the first div. Here is the basic code for it.

.div1{
      height: 100px;
      width: 100px;
}
.div2{
      height: 50px;
      width: 50px;
}

而html是:

<div id = "div2" class="div2">
 <div id="div1" class="div1"></div>
</div>

使用javascript,我希望能够通过按滚动div2(因为这很容易屏幕)在屏幕上的空闲部分并沿div拖动。基本上,滚动功能会像单击和拖动google map时一样。有人可以帮我吗?

Using javascript, I would like to be able to scroll through div2 by pressing (since it is a touch screen) an unoccupied part of the screen and dragging along the div. Basically, the scroll feature would behave the way google maps does when you click and drag in it. Can anybody help me with this? Thanks in advance!

就鼠标操作而言,按下等同于单击此处,只是为了清楚。我也仅在Firefox中工作,因此跨浏览器兼容性不是问题。

In terms of mouse actions, pressing is equivalent to clicking here, just to be clear. I am also working in Firefox only, so cross-browser compatibility is not an issue.

推荐答案

此方法...在您引用FireFox之前,我已经开始将其用于移动设备浏览器了...所以可能一点额外...

This works...I'd started making it for mobile safari before you cited FireFox...so it may have a little extra...

var _startX = 0;
var _startY = 0;
var _offsetX = 0;			
var _offsetY = 0;
var _dragElement;
document.onmousedown = OnMouseDown;
document.onmouseup = OnMouseUp;

function OnMouseDown(event){
  document.onmousemove = OnMouseMove;
    _startX = event.clientX;
  _startY = event.clientY;
  _offsetX = document.getElementById('div1').offsetLeft;
  _offsetY = document.getElementById('div1').offsetTop;
  _dragElement = document.getElementById('div1');

}

function OnMouseMove(event){
    _dragElement.style.left = (_offsetX + event.clientX - _startX) + 'px';
  _dragElement.style.top = (_offsetY + event.clientY - _startY) + 'px';
}

function OnMouseUp(event){
  document.onmousemove = null;
  _dragElement=null;
}

.div1{position:absolute; height:500px; width: 500px; z-index:1; background-color:red;}
.div2{position:absolute; top:100px; left:100px; height:100px; width:100px; z-index:2; overflow:hidden; display:block;}

<div class="div2" id="div2">
  <div class="div1" id="div1">
  </div>
</div>

这篇关于如何通过拖动而不是使用滚动条来滚动div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆