JQuery Draggable / Snap Limit Area

时间:2016-07-29 21:34:36

标签: jquery drag

如何限制“A”可以拖到以下代码中的gameArea div的区域?

我需要添加更多文字才能提交此问题。这够了吗?

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Permutations</title>
<style>
    body{
      font-family: sans-serif;
      font-size: 50px;
      color: green;
    }
    #gameArea{
      margin:20px auto;
      width: 600px;
      height: 400px;
      border: 4px solid green;
      background-color: cyan;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
    $( function() {
      $( "#draggable" ).draggable({ grid: [ 50, 50 ] });
    } );
</script>
</head>
<body>
    <div id="gameArea">
        <p id="draggable">A</p>
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

嘿检查Demo

#include <stdio.h>
#include <stdlib.h>

int average(const char *filename){
  FILE *fp = fopen(filename,"rb");
  if (fp == NULL){
    printf("\nThe file '%s' did not open\n.", filename);
    return -1;
  }

  unsigned long long n = 0;
  unsigned long long sum = 0;
  unsigned char tmp[512];
  size_t read_count;

  while((read_count = fread(tmp, 1, sizeof tmp, fp)) > 0) {
    n += read_count;
    for (size_t i = 0; i<read_count; i++) {
      sum += tmp[i];   
    }
  }
  fclose(fp);

  int avg = 0;
  if (n) {
    avg = (int) (sum/n);
  }
  return avg;
}

并调整#draggable div的宽度

$( function() {
     $( "#draggable" ).draggable({ containment: "parent" , grid: [ 50, 50 ] });
} );

答案 1 :(得分:0)

您可以.droppable()使用#gameArea来确定放置位置的有效性,如下所示:

$(function() {
  $( "#draggable" ).draggable({ 
    grid: [ 50, 50 ],
    revert: "invalid"
  });
  $("#gameArea").droppable({
    accepts: "#draggable"
  });
});