为什么这个JavaScript mousemove功能不起作用?

iBr*_*an2 1 javascript jquery

所以,我正在尝试使这个函数工作,所以无论它应用什么div,pageSee类将跟随一个超链接..

这就是我写的...... 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>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

那里有几个问题:

  1. 声明一个全局divFollow函数不会使它成为jQuery对象的属性.为此,您将其添加到$.fn:

    $.fn.divFollow = function() { /* ... */ };
    
    Run Code Online (Sandbox Code Playgroud)
  2. each函数内部的回调中,this不会是jQuery对象,它将是一个原始的DOM元素.所以你需要将它包装在一个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/'
    });
});
Run Code Online (Sandbox Code Playgroud)

可能还有其他问题,但希望能帮到你.