How do I avoid a click event firing after dragging a gridster.js widget with clickable content?

前端 未结 5 1069
被撕碎了的回忆
被撕碎了的回忆 2021-01-21 15:32

I\'m using Gridster (http://gridster.net/) which able to drag the content inside the li . In my li there is a clickable div.

  • 相关标签:
    5条回答
    • 2021-01-21 15:53

      The problem is that the click event is fired after the mouseup event that is passed to draggable.stop.

      You therefore need to briefly trap that click event and stop it propagating, then untrap it once you've finished so people can subsequently click on the item.

      You can do this like so (click for working JSFiddle):

      $(document).ready(function () {
        // Basic event handler to prevent event propagation and clicks
        var preventClick = function (e) { e.stopPropagation(); e.preventDefault(); };
        $(element).gridster({
          draggable: {
            start: function (event, ui) {
              // Stop event from propagating down the tree on the capture phase
              ui.$player[0].addEventListener('click', preventClick, true);
            },
            stop: function (event, ui) {
              var player = ui.$player;
              setTimeout(function () {
                player[0].removeEventListener('click', preventClick, true);
              });
            }
          }
        });
      })
      

      This is a much better solution than the currently accepted answer, because it avoids having a variable with state being set/checked across multiple components/handlers.

      0 讨论(0)
    • 2021-01-21 15:57

      you should try that :

      var gridster = $(".gridster ul").gridster().data('gridster');
      gridster.disable();
      
      0 讨论(0)
    • 2021-01-21 16:06

      Without digging into the JS, adding onclick = "return false;" to your <a> tag should stop the click from triggering.

      For stopping just the drag, try:

      gridster.draggable.stop(){
         return false;
      }
      

      or

      gridster.draggable.stop(e){
         e.preventDefault();
      }
      
      0 讨论(0)
    • 2021-01-21 16:12

      I fixed it with a trigger variable: var dragged = 0 Add the following to your gridster initialization which sets the variable to 1 on drag start:

      ...
          draggable: {
              start: function(event, ui) {
      
                  dragged = 1;
                  // DO SEOMETHING
              }
          }
      ....
      

      In your click event on the same object, check:

      ...
          if(!dragged){
              // DO SOMETHING
          }
          // RESET DRAGGED SINCE CLICK EVENT IS FIRED AFTER drag stop
      dragged = 0
      ....
      
      0 讨论(0)
    • 2021-01-21 16:17

      There now is a native support to disable the drag and drop operation on Gridster.

      $(".gridster ul").gridster().data('gridster').disable();

      0 讨论(0)
    提交回复
    热议问题