2016-06-26 18 views
1

だから、私はpageSeeクラスは、ハイパーリンクに従います、それが適用されますどのようなdivのように、この機能を動作させるためにしようとしている。..なぜこのJavaScript mousemove関数は動作しませんか?

これは私が書いたものです。.. https://jsfiddle.net/LoorLge5/5/

<html> 
<head> 
<style> 
    body {padding: 500px; background: #ddd; } 
    .pageSee { position: absolute; float: left; } 
</style> 
</head> 

<body id="as"> 

<div id="this">this is awesome</div> 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> 
<script> 
    $(function() 
    { 
     $('#as').divFollow({ 
      target: 'http://www.facebook.com/' 
     }); 
    }); 

    function divFollow(settings) 
    { 
     return this.each(function() 
     {  
      this.append('<a class="pageSee" src="' + settings.target + '"></a>'); 

      this.on('mousemove', function(e) 
      { 
       $('.pageSee').css({ 
        left: e.pageX - 5, 
        top: e.pageY - 5 
       }); 
      }); 
     }); 
    } 
</script> 
</body> 
</html> 

答えて

6

問題のカップルがあります:グローバルdivFollow機能を宣言

  1. はjQueryのオブジェクトのプロパティにする何もしません。これを行うには、あなたが$.fnに追加します。

    $.fn.divFollow = function() { /* ... */ }; 
    
  2. あなたeachのコールバック内で関数内で、thisは、それが生のDOM要素になるだろう、jQueryオブジェクトではありません。だから、jQueryオブジェクトでラップする必要があります:$(this)(あなたがdivFollowであることは非常に正しいです、this jQueryオブジェクトである。)

  3. あなたmousemoveハンドラの中で、あなたはすべて.pageSee要素を見つけていますCSSの変更あなたはおそらく、この特定の要素に関連するものをしたいだけです。

ので、最低でも:

// Put it on `$.fn` 
$.fn.divFollow = function(settings) { 
    return this.each(function() { 
     // Wrap `this` 
     var $this = $(this); 
     $this.append('<a class="pageSee" src="' + settings.target + '"></a>'); 
     $this.on('mousemove', function(e) { 
      // Find the .pageSee within this element only 
      $this.find('.pageSee').css({ 
       left: e.pageX - 5, 
       top: e.pageY - 5 
      }); 
     }); 
    }); 
}; 

$(function() { 
    $('#as').divFollow({ 
     target: 'http://www.facebook.com/' 
    }); 
}); 

他の問題があるかもしれませんが、うまくいけば、あなたは行き​​ますという。

+0

これは完璧でした。私は、それが機能するためのオプション設定も含める必要がありました。 settings = $ .extend({target:null}、設定); – iBrazilian2

関連する問題