jQuery - 可拖动/停留在视口

时间:2017-07-23 13:41:31

标签: javascript jquery html css jquery-ui

以下是我的问题的简短说明:
在我拖动元素之前,它在调整窗口大小后保持在其位置。但是当我开始拖动它时,然后尝试再次调整窗口大小,它将不会停留在其容器中。

这是一个Fiddle来证明我的问题 到目前为止,这是我的代码:

$(document).ready(function() {
  $(".MENU").draggable({
    containment: ".MENU-CONTAINER",
    snap: ".MENU-CONTAINER",
    snapMode: "inner",
    snapTolerance: "16",
    scroll: false
  });
});
* {
  box-sizing: border-box;
}

body {
  background: hsla(0, 0%, 100%, 1.00);
}

.MAIN {
  padding-top: 32px;
  padding-left: 32px;
  width: 100%;
  height: 100%;
}

.MENU-CONTAINER {
  position: fixed;
  width: calc(100% - 64px);
  height: calc(100vh - 64px);
  background-color: hsla(120, 100%, 25%, 0.3);
}

.MENU {
  position: fixed;
  bottom: 32px;
  right: 32px;
  width: 128px;
  height: 64px;
  background: hsla(0, 0%, 0%, 1.00);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<div class="MAIN">
  <div class="MENU-CONTAINER">
    <div class="MENU"></div>
  </div>
</div>

在更改视口大小后是否可以让此元素跟随其容器(即在窗口调整大小后保留包含)?

1 个答案:

答案 0 :(得分:1)

在每个窗口调整大小后添加重新加载

$(window).resize(function(){
    location.reload();
});

演示:

$(".MENU").draggable({
  containment: ".MENU-CONTAINER",
  snap: ".MENU-CONTAINER",
  snapMode: "inner",
  snapTolerance: "16",
  scroll: false
});

$(window).resize(function(){
    location.reload();
});
* {box-sizing: border-box;}

body {background: hsla(0, 0%, 100%, 1.00);}

.MAIN {
  padding-top: 32px;
  padding-left: 32px;
  width: 100%;
  height: 100%;
}

.MENU-CONTAINER {
  position: fixed;
  width: calc(100% - 64px);
  height: calc(100vh - 64px);
  border: 1px solid blue;
}

.MENU {
  position: fixed;
  bottom: 32px;
  right: 32px;
  width: 128px;
  height: 64px;
  background: hsla(0, 0%, 0%, 1.00);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="MAIN">
  <div class="MENU-CONTAINER">
    <div class="MENU"></div>
  </div>
</div>