简体   繁体   English

存在一个类的多个项目时的jQuery定位

[英]Jquery targeting when multiple items of a class exist

I have the following code: 我有以下代码:

$(function () {
        var target = $('span.slider') //can I make the variable apply to the target span?

        target.mousedown(function() { 
              sliding = true 
        })
        $(document).mouseup(function() {
             sliding = false 
        })
        $(document).mousemove(function(e) { 
            if(sliding){ 
              target.css('left', e.pageX) //do I isolate here?
            }
        })  
    })

There are four 'span.slider' in my html. 我的html中有四个“ span.slider”。 How do I modify this jquery so that the functionality only applies to the target span.slider? 如何修改此jquery,使其功能仅适用于目标span.slider? The code above moves all four spans, and I completely understand why it does. 上面的代码移动了所有四个范围,我完全理解为什么会这样。 I am having trouble targeting it to just the span the user wishes to move. 我在将其定位到用户希望移动的范围时遇到麻烦。

Try adding a class to it and then check against the class 尝试向其中添加一个类,然后对照该类进行检查

    target.mousedown(function() { 
          sliding = true;
          $(this).addClass('sliding'); 
    })
    $(document).mouseup(function() {
         sliding = false; 
          target.removeClass('sliding'); 
    })
    $(document).mousemove(function(e) { 
        if(sliding){ 
          target.filter('.sliding').css('left', e.pageX) //do I isolate here?
        }
    })  

Try this: 尝试这个:

$(function() {
    var target = $('span.slider'); //can I make the variable apply to the target span?
    var targetToMove;
    target.mousedown(function() {
        sliding = true;
        targetToMove = $(this);
    });
    $(document).mouseup(function() {
        sliding = false;
    });
    $(document).mousemove(function(e) {
        if (sliding) {
            targetToMove.css('left', e.pageX); //do I isolate here?
        }
    });
})​;​

You can bind and unbind the mousemove each time as follows 您可以每次按以下方式绑定和取消绑定mousemove

$(function() {
  var target = $('span.slider');
  target.on('mousedown', function(e) {
    var $el = $(this)
    $(document).mousemove(function(e) {
      $el.css('left', e.pageX) 
    })
  }).on('mouseup', function() {
    $(document).off('mousemove');
  })

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM