【问题标题】:How to cancel click after resizable events?如何在可调整大小的事件后取消点击?
【发布时间】:2026-01-07 05:00:01
【问题描述】:

我正在使用 Jquery UI 可调整大小插件来调整各种 div 的大小。考虑以下 HTML 页面(嵌入了 JS):

<html>
<head></head>
<body>
<div id="site">
    <div>This element is resizable</div>
    <br />
    <div style="width: 200px;">This is another resizable element</div>
</div>

<!-- javascript includes -->
<script>
$(function() {
    $("#site div").click(function() {

        console.log("Clicked");    
        if($(this).hasClass("selected")) {
            $(this).removeClass("selected");
        }
        else {        // Currently not selected, so let's select it        
            $(this).addClass("selected").resizable({
                start: function(event, ui) {
                    console.log("Start");
                },
                resize: function(event, ui) {
                    console.log("Resize");
                },
                stop: function(event, ui) {
                    console.log("Stop");
                }
            });
        }
    });
});
</script>
</body>
</html>

因此,我在此示例代码中要完成的工作非常简单。当用户单击嵌套在“#site”中的 div 时,我希望 div 成为“选中”。所以,在这个例子中,当 div 的点击事件被触发时,一个名为“selected”的 CSS 类将被添加到被点击的 div 中。除了点击 div 之外,用户还可以调整 div 的大小。当用户调整所选 div 的大小时,就会出现问题。显然,当用户第一次选择 div 时会触发 click 事件,但是当用户单击并拖动 div 的边缘以调整其大小时也会触发 click 事件。点击事件将调用点击例程并取消选择 div。这不是我想要发生的。只有在所有可调整大小的事件都触发后才会触发 click 事件。

因此,我的问题是,我如何处理这种情况以允许用户单击并选择 div,同时还允许调整 div 的大小,但在拖动和调整 div 的大小时不取消选择?感谢您的帮助。提前致谢。

【问题讨论】:

    标签: jquery jquery-ui-resizable


    【解决方案1】:

    好问题。可调整大小正在利用事件冒泡。实际的调整大小手柄是可调整大小的内部元素。因此,检查事件目标的类将为您提供所需的内容。

    http://jsfiddle.net/bmvDs/1/

    $('#test').click(function(e){
        if(!$(e.target).is('.ui-resizable-handle')) // not if it is the handle
            $(this).toggleClass('selected');
    }).resizable();
    

    【讨论】:

      【解决方案2】:

      一种选择可能是从一开始就将所有 div 设置为可调整大小并在点击时处理样式:

      $(function() {
          var resizables = $('#site div');
          resizables.resizable({
      
                     start: function(event, ui) {
                          console.log("Start");
      
                          // Remove the selected class from all other divs first
                          resizables.each(function(){ $(this).removeClass('selected'); });
      
                          // Set this div as selected
                          ui.element.addClass('selected');
                          // Carry on doing whatever else you want to do
      
                     },
                     resize: function(event, ui) {
                          console.log("Resize");
                     },
                     stop: function(event, ui) {
                          console.log("Stop");
                     }
      
          });
      });
      

      【讨论】:

        【解决方案3】:

        jQuery .one 是你的朋友!这将允许单击类为 .foo 的每个元素。

        $(".foo").one("click", function() {
          alert("This will be displayed only once.");
        });
        

        【讨论】: