[英]Why isn't this JavaScript mousemove function working?
因此,我正在尝试使此函数起作用,以便无论将其应用于哪个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>
那里有两个问题:
声明全局divFollow
函数不会使其成为jQuery对象的属性。 为此,将其添加到$.fn
:
$.fn.divFollow = function() { /* ... */ };
在函数中each
回调的内部, this
不是jQuery对象,而是原始DOM元素。 因此,您需要将其包装在一个jQuery对象中: $(this)
(您完全正确,在divFollow
, this
是一个jQuery对象。)
在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/'
});
});
可能还有其他问题,但希望可以解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.