有问题的scrollTo()方法

时间:2013-02-11 19:30:00

标签: javascript html5

我想在div中使用鼠标滚动图像,但是无法找到正确的X和Y坐标值来移动图像。下面是我的示例代码..我可以滚动图像 ,不用 DIV。如果我在这里做错了,有人可以帮忙。

<html>
<head>
<script type="text/javascript">


document.onmousedown = function(){

var e=arguments[0]||event;
var x=getWindowSize()[2],y=getWindowSize()[3],mx=e.clientX,my=e.clientY;
document.onmousemove=function(){
var e=arguments[0]||event;
window.scrollTo(x+(mx-e.clientX), y+(my-e.clientY));


return false;
}
document.onmouseup=function(){
document.onmousemove=null;
}
return false;
}


function getWindowSize(){
if (window.innerHeight) return [window.innerWidth-10,window.innerHeight-10,window.pageXOffset,window.pageYOffset];
else if (document.documentElement.clientHeight) return [document.documentElement.clientWidth-10,document.documentElement.clientHeight-10,document.documentElement.scrollLeft,document.documentElement.scrollTop];
return [document.body.clientWidth,document.body.clientHeight,document.body.scrollLeft,document.body.scrollTop];
}


</script> 


</head>
<body style="overflow:hidden">


<div id="mydiv" style="overflow:auto;position:absolute; height:300px;">
 <img src="img1.png" />

 </div>



</body>
</html>

1 个答案:

答案 0 :(得分:0)

使用带遮罩的img来估计正确的滑动百分比。

HTML:

<div id="div">
  <img id="img" src="http://www.fastcodesign.com/multisite_files/codesign/imagecache/960/article_feature/1280-army-of-luck-013.jpg" />
  <div id="msk"></div>
</div>

CSS

#div {
  position:absolute;
  overflow:hidden;
  height:300px;
  width:500px;
  border:1px solid blue;
  cursor:move;
  position:relative;
}
#img {
  position:absolute;
}
#msk {
  position:absolute;
  width:100%;
  height:100%;
  background-color:rgba(255,255,0,.5);
  z-index:2;
}

JS:

var img = document.getElementById('img');
var msk = document.getElementById('msk');
document.onmousedown = function(e){
  document.onmousemove = function(e){
  if(e.target != msk) return;
  var x = e.clientX;
  var y = e.clientY;
  var mw = msk.offsetWidth;
  var mh = msk.offsetHeight;
  var iw = img.offsetWidth;
  var ih = img.offsetHeight;
  // your formula goes here
  img.style.left = Math.max(-(x/mw)*(iw),-mw) + "px";
  img.style.top = Math.max(-(y/mh)*(ih),-mh) + "px";
}
}
document.onmouseup = function(e){
      if(e.target != msk) return;
  document.onmousemove = $.noop;
}

http://codepen.io/anon/pen/vlKJq