【问题标题】:How to make the page to scroll to the left when elements placed in a negative position?当元素放置在负位置时如何使页面向左滚动?
【发布时间】:2017-11-28 22:57:19
【问题描述】:

我正在尝试创建一个类似于思维导图的应用程序,但它不必那么复杂。我遇到的问题是,当我在页面上放置一个元素并使用 jQuery 可拖动功能使其可拖动时,该元素可以向右拖动,并且当您拖动元素时页面的宽度会增加,但是当您将元素拖动到left 获得负值,滚动条不会覆盖负空间。

我到处搜索,找不到任何东西。任何帮助将不胜感激。

JavaScript 代码

$( function() {
    $("#draggable").draggable();
});

HTML 标记:

  <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>
  <div id="draggable">
  Can be dragged to the right of the screen and the scrollbar increases but 
  not to the left.
  </div>

JSFiddle Example

【问题讨论】:

    标签: javascript css scrollbar positioning jquery-ui-draggable


    【解决方案1】:

    滚动条不应该向页面的顶部或左侧延伸,但是如果将可拖动对象拖放到负坐标并重置其位置,您可以使用 javascript 通过增加页面大小来解决此问题,例如

    var increasedLeft = 0;
    
    $(function() {
      $("#draggable").draggable({
        stop: function(event, ui) {
          if (ui.position.left < 0) {
            $("#draggable").css({left: 0});
            $("#container").width($("#container").width() - ui.position.left);
            increasedLeft -= ui.position.left;
          } else if (increasedLeft > 0) {
          	$("#container").width($("#container").width() - Math.min(increasedLeft, ui.position.left));
            $("#draggable").css({left: (ui.position.left - Math.min(increasedLeft, ui.position.left))});
          	increasedLeft -= Math.min(increasedLeft, ui.position.left);
          }
        }
      });
    });
    html, body, #container {
      width: 100%;
      height: 100%;
      margin: 0;
    }
    
    #draggable {
      background-color: black;
      color: white;
      width: 200px;
      margin: 0;
    }
    <body>
      <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>
      <div id="container">
        <div id="draggable">
          Can be dragged to the right of the screen and the scrollbar increases but not to the left.
        </div>
      </div>
    </body>

    【讨论】:

    • 谢谢,现在应该这样做了。
    • @HamidHosseini 没问题!如果我的回答解决了您的问题,您可以通过单击答案左侧的复选标记来接受它作为正确答案。
    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多