欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS实现利用闭包判断Dom元素和滚动条的方向示例

程序员文章站 2023-10-20 13:30:37
本文实例讲述了js实现利用闭包判断dom元素和滚动条的方向。分享给大家供大家参考,具体如下: 一、判断滚动条的方向,利用闭包首先保存滚动条的位置,然后当滚动时候不断更新滚...

本文实例讲述了js实现利用闭包判断dom元素和滚动条的方向。分享给大家供大家参考,具体如下:

一、判断滚动条的方向,利用闭包首先保存滚动条的位置,然后当滚动时候不断更新滚动初始值,然后通过差指判断方向

function scroll(fn) {
    //利用闭包判断滚动条滚动的方向
    var beforescrolltop = document.body.scrolltop,
      fn = fn || function() {};
    window.addeventlistener("scroll", function() {
      var afterscrolltop = document.body.scrolltop,
        delta = afterscrolltop - beforescrolltop;
      if (delta === 0) return false;
      fn(delta > 0 ? "down" : "up");
      beforescrolltop = afterscrolltop;
    }, false);
}
scroll(function(direction) { console.log(direction) });

二、判断鼠标的移动方向

function direction() {
    var lastx = null,
      lasty = null;
    window.addeventlistener("mousemove", function(event) {
      var curx = event.clientx,
        cury = event.clienty,
        direction = '';
      // console.info(event);
      // console.info(event.clientx);
      // console.info(event.clienty);
      // 初始化坐标
      if (lastx == null || lasty == null) {
        lastx = curx;
        lasty = cury;
        return;
      }
      if (curx > lastx) {
        direction += 'x右,';
      } else if (curx < lastx) {
        direction += 'x左,';
      }
      if (cury > lasty) {
        direction += 'y下';
      } else if (cury < lasty) {
        direction += 'y上';
      }
      lastx = curx;
      lasty = cury;
      //console.info(direction);
      document.getelementbyid("test").innertext = direction;
    })
}

三、判断鼠标进入和出去某dom元素的方式,这种没有利用闭包原理

var gaga = function(wrap) {
    var wrap = document.getelementbyid(wrap);
    var hoverdir = function(e) {
      var w = wrap.offsetwidth,
        h = wrap.offsetheight,
        x = (e.clientx - wrap.offsetleft - (w / 2)) * (w > h ? (h / w) : 1),
        y = (e.clienty - wrap.offsettop - (h / 2)) * (h > w ? (w / h) : 1),
        // 上(0) 右(1) 下(2) 左(3) 
        direction = math.round((((math.atan2(y, x) * (180 / math.pi)) + 180) / 90) + 3) % 4,
        eventtype = e.type,
        dirname = new array('上方', '右侧', '下方', '左侧');
      if (e.type == 'mouseover' || e.type == 'mouseenter') {
        wrap.innerhtml = dirname[direction] + '进入';
      } else {
        wrap.innerhtml = dirname[direction] + '离开';
      }
    }
    if (window.addeventlistener) {
      wrap.addeventlistener('mouseover', hoverdir, false);
      wrap.addeventlistener('mouseout', hoverdir, false);
    } else if (window.attachevent) {
      wrap.attachevent('onmouseenter', hoverdir);
      wrap.attachevent('onmouseleave', hoverdir);
    }
}