Мне нужно преобразовать следующее событие mousewheel в вызываемую функцию - PullRequest
0 голосов
/ 23 августа 2011

#horiz будет любым общим тегом, к которому я хочу применить код, выделенный жирным шрифтом.Я использую jScrollPane и библиотеку jQuery MouseWheel.

$("#horiz").mousewheel(function(event, delta) {
    **event.preventDefault();
    $(this).find(".jspPane").animate({"left": "+=" + (50 * delta) + "px"}, 0);
    $(this).find(".jspPane").css("left").replace(/[^-\d\.]/g, '') > 0 ? $(this).find(".jspPane").animate({"left": "0px"}, 0) : null;
    $(this).find(".jspPane").css("left").replace(/[^-\d\.]/g, '') < (($(this).find("#scrollText").css("width").replace(/[^-\d\.]/g, '') - $(this).css("width").replace(/[^-\d\.]/g, '')) * -1) ? $(this).find(".jspPane").animate({"left": (($(this).find("#scrollText").css("width").replace(/[^-\d\.]/g, '') - $(this).css("width").replace(/[^-\d\.]/g, '')) * -1) + "px"}, 0) : null;
    if($(this).find(".jspTrack").css("width").replace(/[^-\d\.]/g, '') - $(this).find(".jspDrag").css("width").replace(/[^-\d\.]/g, '') == $(this).find(".jspDrag").css("left").replace(/[^-\d\.]/g, '')) {
        //Track End - Right
    } else if ($(this).find(".jspDrag").css("left").replace(/[^-\d\.]/g, '') == 0) {
        //Track End - Left
    } else {
        //Track Mid - Anywhere between ends
    }**
});

Ответы [ 2 ]

1 голос
/ 23 августа 2011

Вы применяете этот код, привязывая событие .mousewheel к определенному элементу с помощью идентификатора (надеюсь, у вас есть только один элемент с id = horiz на странице). Вы можете сделать это для любого элемента на странице, используя классы вместо и ID.

Это применило бы вашу функцию к элементу с Id horiz и к любому элементу на странице с классом myMouseWheelBinding

$("#horiz, .myMouseWheelBinding").mousewheel(function(event, delta) { 
   //Your code here
});

или просто не указывайте идентификатор и используйте класс (не забудьте добавить класс к элементу horiz)

$(".myMouseWheelBinding").mousewheel(function(event, delta) { 
   //Your code here
});

Html

<div class="myMouseWheelBinding"...
1 голос
/ 23 августа 2011

Всякий раз, когда у вас есть тонна вызовов, которые вам нужно выполнить для определенного объекта DOM, обычно лучше обернуть функциональность в плагин jQuery.В долгосрочной перспективе ваш код будет более легок в обслуживании.

$(document).ready(function() {

    $.extend({

      myMouseScrollable: function() {

        return this.each(function() {

          var $self = $self;
          var $jsPane = $self.find(".jsPane");
          var OnMouseScroll = function(event, delta) {

             $jsPane.animate({"left": "+=" + (50 * delta) + "px"}, 0);
             $jsPane.css("left").replace(/[^-\d\.]/g, '') > 0 ? $jsPane.animate({"left": "0px"}, 0) : null;
             $jsPane.css("left").replace(/[^-\d\.]/g, '') < (($self.find("#scrollText").css("width").replace(/[^-\d\.]/g, '') - $self.css("width").replace(/[^-\d\.]/g, '')) * -1) ? $jsPane.animate({"left": (($self.find("#scrollText").css("width").replace(/[^-\d\.]/g, '') - $self.css("width").replace(/[^-\d\.]/g, '')) * -1) + "px"}, 0) : null;
             if($self.find(".jspTrack").css("width").replace(/[^-\d\.]/g, '') - $self.find(".jspDrag").css("width").replace(/[^-\d\.]/g, '') == $self.find(".jspDrag").css("left").replace(/[^-\d\.]/g, '')) {
                  //Track End - Right
             } else if ($self.find(".jspDrag").css("left").replace(/[^-\d\.]/g, '') == 0) {
                  //Track End - Left
              } else {
                  //Track Mid - Anywhere between ends
              }**
          }

          $self.mousewheel(OnMouseScroll);


        });

      }

    });

  });

Теперь, когда вам нужно применить это событие к новому объекту, вы просто:

$("#horiz").myMouseScrollable();

Я взял некоторые возможности оптимизациис кодом, который вы имели.Это всегда хорошая идея, чтобы кэшировать ваши селекторы, а не использовать их снова и снова.

в частности повторные вызовы $self.find('.jsPane');

...