javascript - 使可拖动元素响应页面

标签 javascript jquery html css jquery-ui

我有一个可调整大小和可拖动的 div,但无法使其响应窗口,我给了 20%,但如果我改变窗口大小,即使我给出了属性,位置也不会根据窗口改变在窗口百分比中,我想要根据窗口百分比拖动元素的位置和大小,任何人都可以帮助解决这个问题

$('div').resizable();
$('div').draggable({
  appendTo: 'body',
  start: function(event, ui) {
    isDraggingMedia = true;
  },
  stop: function(event, ui) {
    isDraggingMedia = false;
  }
});
<html>

<head>
  <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/cupertino/jquery-ui.css" />
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>

<body>
  <div style="border:1px solid #00FF7F;position:absolute; display:inline-block; top:20%;left:20%;  width:26%; height:26% ; overflow:hidden;">
    <img style="  width:100%; height:100%" src="http://www.clipartkid.com/images/68/baby-toys-jpg-19-feb-2010-10-37-50k-FSIRmi-clipart.jpg" />
  </div>

</body>

</html>

最佳答案

如果不清楚您要实现的目标,很难知道这是否对您有帮助。

工作示例:https://jsfiddle.net/Twisty/ch3fhs3o/

HTML

<div class="diag">
  <img src="https://www.clipartkid.com/images/68/baby-toys-jpg-19-feb-2010-10-37-50k-FSIRmi-clipart.jpg" />
</div>

CSS

.diag {
  border: 1px solid #00FF7F;
  position: absolute;
  display: inline-block;
  overflow: hidden;
}

.diag img {
  width: 100%;
  height: 100%;
}

JavaScript

$(function() {
  var isDraggingMedia;
  $(".diag").css({
    width: Math.round($(window).width() * 0.26) + "px",
    height: Math.round($(window).height() * 0.26) + "px",
    top: Math.round($(window).height() * 0.20) + "px",
    left: Math.round($(window).width() * 0.20) + "px"
  });
  $(".diag").resizable();
  $(".diag").draggable({
    appendTo: 'body',
    start: function(event, ui) {
      isDraggingMedia = true;
    },
    stop: function(event, ui) {
      isDraggingMedia = false;
    }
  });
  $(window).resize(function() {
    console.log("Window Width:", $(window).width(), "Height:", $(window).height());
    var dW = Math.round($(window).width() * 0.26);
    var dH = Math.round($(window).height() * 0.26);
    var dL = Math.round($(window).width() * 0.20);
    var dT = Math.round($(window).height() * 0.20);
    console.log("Dialog Width:", dW, "Height:", dH);
    $(".diag").css({
      width: dW + "px",
      height: dH + "px",
      top: dT + "px",
      left: dL + "px"
    }).trigger("resize");
  })
});

我更喜欢设置一个类名以便于选择。您可以看到,当 window 调整大小时,它也会调整大小并重置 top, left 可拖动对象。

这里有一些注意事项,但我不确定这是否是您要再次寻找的内容。

关于javascript - 使可拖动元素响应页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43627916/

相关文章:

javascript - gorilla /csrf 的问题

初学者的 PHP 编码帮助

html - URL 的字符数限制是多少

javascript - 如何对编译后的代码进行单元测试(使用QUnit和Sinon)(闭包编译器高级编译)

javascript - 如何防止选择html文本区域内容时字符位置发生变化

javascript - 如何从 Firefox 插件连接到 mongodb

javascript - 在动态图库中预加载接下来的几张图片

javascript - Angular - 未选择编辑角色

jquery - jQuery 的 ondragstart 事件

javascript - 单击后删除类