拖放及按扣选项


说明

该选项用于使可拖动格按照网格捕捉或限制其移动范围。

  • 如果设置为 false(默认选项),则不会发生捕捉或限制。

  • 如果为整数 x,则可拖动格将捕捉到 x 像素的网格。

  • 如果为数组 [x, y],则水平拖动会捕捉到 x 像素的网格,而垂直拖动会捕捉到 y 像素的网格。

  • 它也可以是一个符合 Function( x , y , draggable ) 的函数,返回一个数组 [x, y]。

语法

以下是使用snap 选项的各种语法。

// Snap target to a 50-pixel grid while dragging
new Draggable('element', {snap:50});

OR

// Constrain dragging to a 100x50px box
new Draggable('element', {
   snap: function(x, y) {
      return[ (x < 100) ? (x > 0 ? x : 0 ) : 100, (y < 50) ? (y > 0 ? y : 0) : 50 ];
   }
});

OR

// Constrain dragging to element's parent node
new Draggable('element', {
   snap: function(x, y, draggable) {
      function constrain(n, lower, upper) {
         if (n > upper) 
            return upper;
         else if (n < lower) 
            return lower;
         else 
            return n;
      }
		
      var element = draggable.element.getDimensions( );
      var parent = draggable.element.parentNode.getDimensions( );
      return [
         constrain(x, 0, parent.width - element.width),
         constrain(y, 0, parent.height - element.height)
      ];
   }
});

示例

<html>
   <head>
      <title>Draggables Elements</title>
		
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      <script type = "text/javascript" src = "/javascript/scriptaculous.js"></script>
		
      <script type = "text/javascript">
         window.onload = function() {
            new Draggable(
               'myimage', {
                  revert:true, snap: function(x, y) {
                     return[
                        (x < 100) ? (x > 0 ? x : 0 ) : 100,
                        (y < 50) ? (y > 0 ? y : 0) : 50
                     ];
                  }
               } 
            );
         }
      </script>
   </head>
   
   <body>
      <p>Try to drag the following image out of its defined
         boundary and see the result. Later change its boundary and
         repeat the exercise.</p>
      <img id = "myimage" src = "/images/scriptaculous.gif"/>
   </body>
</html>

这将产生以下结果−

scriptaculous_drag_drop.htm
广告