某个div有横向和纵向两个滚动条,滚动时有什么办法可以知道当前是横向还是纵向滚动吗?查了一下貌似只有onscroll事件。。

解决方案 »

  1.   

    判断scrollLeft和scrollTop属性就知道了<div style="width:200px;height:200px;overflow:auto" id="div1">
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    <br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1
    </div>
    <script type="text/javascript">
    window.onload=function(){
      document.getElementById('div1').onscroll=function(){
         var sl=this.scrollLeft,st=this.scrollTop
         ,ost=this.getAttribute('ost'),osl=this.getAttribute('osl');
     if(sl!=osl)alert('水平滚动');
     if(st!=ost)alert('垂直滚动');
     this.setAttribute('ost',st);
     this.setAttribute('osl',sl);
      }
    }
    </script>
      

  2.   

    ++
    加个默认值就更好些。否则"第一次scroll"时,因为ost和osl的值均为null,会判定为两种状态同时出现
    window.onload=function(){
       var o=document.getElementById('div1');
       o.setAttribute('osl',o.scrollLeft)
       o.setAttribute('ost',o.scrollTop);
       o.onscroll=function(){
        var sl=this.scrollLeft,
            st=this.scrollTop,
            ost=this.getAttribute('ost'),
            osl=this.getAttribute('osl');
        if(sl!=osl)alert('水平滚动');
        if(st!=ost)alert('垂直滚动');
        this.setAttribute('ost',st);
        this.setAttribute('osl',sl);
      }
    }