首先,我很抱歉,但我是一个非常大的初学者.
我真的不明白jquery插件中的"this",看起来很多但是找不到任何答案.
这是我的插件(我只是为了练习这个)
jQuery.fn.hoverPlugin = function(){
var element = this;
$(element).animate({"opacity" : ".5"});
$(element).hover(function(){
$(element).stop().animate({"opacity" : "1"});
}, function() {
$(element).stop().animate({"opacity" : ".5"});
});
};
Run Code Online (Sandbox Code Playgroud)
电话
$("img").hoverPlugin();
Run Code Online (Sandbox Code Playgroud)
我的问题是这样它会在所有图像上添加动画效果.如果对页面上的所有图像进行动画加载都没关系,但是当我将鼠标放在图像上时,它会动画全部动画.
如果我以简单的方式写它
$("img").animate({"opacity" : ".5"});
$("img").hover(function(){
$(this).stop().animate({"opacity" : "1"});
}, function() {
$(this).stop().animate({"opacity" : ".5"});
});
Run Code Online (Sandbox Code Playgroud)
它按我想要的方式工作.
因此,如果一个更有经验的开发人员可以向我解释如何在我的插件中进行此操作?我会很开心的.
谢谢
那是因为this在.hoverPlugin函数中引用了$('img')用来调用它:
jQuery.fn.hoverPlugin = function(){
var element = this;
$(element).animate({"opacity" : ".5"});
$(element).hover(function(){
$(element).stop().animate({"opacity" : "1"});
}, function() {
$(element).stop().animate({"opacity" : ".5"});
});
};
$(document).ready(function(){
$("img").hoverPlugin();
});
Run Code Online (Sandbox Code Playgroud)
如果你尝试console打开,你会明白我的意思.
如果你改成这个:
$(element).hover(function(){
$(this).stop().animate({"opacity" : "1"});
}, function() {
$(this).stop().animate({"opacity" : ".5"});
});
Run Code Online (Sandbox Code Playgroud)
有用.
这更好:
jQuery.fn.hoverPlugin = function(){
this
.animate({"opacity" : ".5"})
.hover(function(){
$(this).stop().animate({"opacity" : "1"});
}, function() {
$(this).stop().animate({"opacity" : ".5"});
});
};
Run Code Online (Sandbox Code Playgroud)
你不需要element,只需使用this和链.