首页 文章

重新制作一个JQuery函数,允许它随时被调用

提问于
浏览
-1

我知道's a stupid question but I'对JQuery很新,我有一个很好的基本问题...这个函数在_58638上被调用_我怎么能重新制作它以便我可以随时调用它?

$(document).on('mousemove', function(e){
	$('#cursor').css({
		left:	e.pageX - 7,
		top:	e.pageY - 7
	});
});

2 回答

  • 0

    由于您需要在嵌套函数中使用指针坐标,因此您可以在某些变量中跟踪它们 .

    var posX, posY;
    
    $(document).on('mousemove', function(e){
        $('#cursor').css({
            left:   e.pageX - 7,
            top:    e.pageY - 7
        });
        posX = e.pageX;
        posY = e.pageY;
    
    });
    
    function parentFunction(){
       //Some code
    
       $('#cursor').css({
            left:   posX - 7,
            top:    posY - 7
        });
    }
    
    parentFunction();
    
  • 0

    您可以这样做(请参阅代码中的注释):

    $(document).ready(function() {
    
      // setup an object to store mouse position
      var mousepos = {};
      // update the object on mousemove
      $(document).on('mousemove', function(e) {
        mousepos = {
          x: e.pageX,
          y: e.pageY
        }
      });
    
      // setup a function to update cursor position
      function setCursor() {
        $('#cursor').css({
          left: mousepos.x - 7,
          top: mousepos.y - 7
        });
      }
    
      // your code
      list = {
        execute: function() {
          // Some code and the nested function 
          setCursor();
        }
      };
    
      list.execute();
    
    });
    

    希望能帮助到你 .

相关问题