如何禁用 jQuery-ui 可拖动小部件?

jqueryweb developmentfront end technology

我们可以借助 jQuery UI 的"可拖动禁用"选项来禁用可拖动小部件。

jQuery 是一个 JavaScript 库,它使用各种辅助方法和属性帮助我们轻松高效地操作 DOM。它允许我们为 DOM 添加交互性,以及添加和更改 DOM 元素的 CSS 样式。

语法

$(element).draggable({ disabled: true })

我们将在应用程序中使用以下 jQuery 链接 -

<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />

上面提供的代码片段是一个链接标签,用于从 jQuery UI 库导入 CSS 文件。

示例 1

在此示例中,我们将创建一个禁用了可拖动元素的容器。

文件名:index.html

<html lang="en">
<head>
   <title>How to disable a jQuery-ui draggable of widget?</title>
   <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
   <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
   <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

   <style>
      .draggable {
         width: 150px;
         height: 150px;
         padding: 0.5em;
         float: left;
         margin: 10px 10px 10px 0;
      }
      #draggable { background-color: red; }
   </style>
</head>
<body>
   <h3>How to disable a jQuery-ui draggable of widget?</h3>
   <div class="draggable" id="draggable"></div>
   <script>  
      $(document).ready(function() {  
         $('#draggable').draggable({
            disabled: true
         });
      });  
   </script>  
</body>
</html>

示例 2

在本例中,我们将创建一个 div 容器,并使用两种方法禁用它:通过小部件禁用选项禁用它,以及使用 destroy 方法禁用它。

文件名:index.html

<html lang="en">
<head>
   <title>How to disable a jQuery-ui draggable widget?</title>
   <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
   <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
   <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

   <style>
      .draggable {
          width: 150px;
          height: 150px;
          padding: 0.5em;
          margin: 10px 10px 10px 0;
      }
      #draggable { background-color: red; }
   </style>
</head>
<body>
   <h3>How to disable a jQuery-ui draggable widget?</h3>
   <div class="draggable ui-state-default" id="draggable"></div>
   <button id="button1">Click to disable the draggability of the above container (Using widget disable option)</button>
   <button id="button2">Click to disable the draggability of the above container (Using destroy method)</button>
   <script>  
      $(document).ready(function() {
         $('#draggable').draggable({
             disabled: false
         });
         // 方法 1:通过小部件禁用选项禁用它
         $('#button1').click(function() {
         });
      
         // 方法二:使用destroy方法
         $('#button2').click(function() {
            $('#draggable').draggable('destroy');
         });
      });  
   </script>  
</body>
</html>

总结

在本文中,我们通过两个不同的示例学习了如何禁用 jQuery UI 可拖动小部件。在第一个示例中,我们创建了一个默认禁用拖动功能的基本 div 容器;在第二个示例中,我们通过点击两个按钮来禁用拖动功能,其中一个按钮使用了 destroy 方法,另一个按钮使用了 disable 方法。


相关文章