31.JS

118. 事件的拖拽

window.onload = function () {
  /**
   * 拖拽box1元素
   *  - 拖拽的流程:
   *      1. 当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown
   *      2. 当鼠标移动时被拖拽元素跟随鼠标移动   onmousemove
   *      3. 当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
   */
  var box1 = document.getElementById("box1");

  // 当鼠标按下
  box1.onmousedown = function (event) {

      // div的偏移量 鼠标.clientX - 元素.offsetLeft
      // div的偏移量 鼠标.clientY - 元素.offsetTop
      var ol = event.clientX - box1.offsetLeft;
      var ot = event.clientY - box1.offsetTop;

      // 当鼠标移动(为document绑定)
      document.onmousemove = function (event) {
          event = event || window.event;
          var left = event.clientX - ol;
          var top = event.clientY - ot;

          box1.style.left = left + "px";
          box1.style.top = top + "px";
      };
      // 当鼠标松开(为document绑定)
      document.onmouseup = function () {
          // 取消移动事件
          document.onmousemove = null;
          // 取消离开事件
          document.onmouseup = null;
      };

      /**
       * 当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容
       * 此时会导致拖拽功能的异常,这个是浏览器提供的默认行为,
       * 如果不希望发生这个行为,则可以通过return false来取消默认行为
       */
      return false;
  };

120. 鼠标滚动事件

// 鼠标滚轮向下滚动,box1变长
// 鼠标滚轮向上滚动,box1变短
window.onload = function () {
    let box1 = document.getElementById('box1');
    /**
     * 绑定一个鼠标滚轮滚动的事件
     * onmousewheel鼠标滚轮滚动的事件,会在滚轮滚动时触发,
     * 但是火狐不支持
     */
    box1.onmousewheel = function (event) {
        event = event || window.event;
        // 判断鼠标滚轮滚动的方向
        // event.wheelDelta可以获取鼠标滚轮滚动的方向
        // wheelDelta这个值我们只看正负不看大小
        if (event.wheelDelta > 0) {
            box1.style.height = box1.clientHeight - 10 + 'px';
        } else {
            box1.style.height = box1.clientHeight + 10 + 'px';
        }

        /**
         * 当滚轮滚动时,如果浏览器有滚动条,滚动条会随之滚动
         * 这是浏览器的默认行为,如果不希望发生,则可以取消默认
         *
         * 使用addEventListener()方法绑定响应函数,取消默认行为时,
         * 不能使用return false需要使用event.preventDefault()来取消默认行为
         */
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_34273481/article/details/87582734
今日推荐