Javascript jquery将悬停元素传递给函数
我有许多带有html类“panel”的选项卡。当用户将鼠标悬停在选项卡上时,不透明度变为0.4。当他们将鼠标移出选项卡时,不透明度变为正常。这是我的代码,但不起作用。开发工具上未报告任何错误。它可能与传递给函数的悬停元素有关。在这种情况下,“事件”和“$(此)”是什么 index.htmlJavascript jquery将悬停元素传递给函数,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有许多带有html类“panel”的选项卡。当用户将鼠标悬停在选项卡上时,不透明度变为0.4。当他们将鼠标移出选项卡时,不透明度变为正常。这是我的代码,但不起作用。开发工具上未报告任何错误。它可能与传递给函数的悬停元素有关。在这种情况下,“事件”和“$(此)”是什么 index.html <div class="panel"> text text text </div> <div class=
<div class="panel">
text text text
</div>
<div class="panel ">
text text text
</div>
您正在调用函数,而不是将它们传递给
.on()
方法(并且您正在使用未声明的事件
变量)。试试这个:
$(".panel").on("mouseover", hoverUnownedPT)
.on("mouseout", stopHoveringUnownedPT);
如果您正在使用,您的浏览器控制台可能至少会发现代码中的一个问题。正如前面提到的另一个答案,您正在调用函数而不是将其作为回调传递,省略()传递实际的函数对象 你想要的是:
$(".panel").on("mouseover", hoverUnownedPT)
.on("mouseout", stopHoveringUnownedPT);
或者:
$(".panel").on("mouseover", function(){
hoverUnownedPT($(this));
})
.on("mouseout", function(){
stopHoveringUnownedPT($(this));
});
function hoverUnownedPT(panel){
panel.css({
"opacity": "0.4",
"filter": "alpha(opacity:40)"
});
}
function stopHoveringUnownedPT(panel){
panel.css({
"opacity": "1",
"filter": "alpha(opacity:100)"
});
}
如果这不能帮助您理解$(this)操作符的用途,那么它表示当前对象在其使用的任何范围内。在本例中,您以前的代码表示实际的函数对象本身,因此不起作用
您可以通过执行以下类似操作并观察输出来测试这一点:
function testMe(x) {
this.x = x;
}
var testInstance = new testMe(10);
alert(testInstance.x);
阅读更多关于“this”的信息。您可以简单地使用css,而无需使用javascript,使用:hover和css3转换来实现平滑
.panel {
-webkit-transition: all 200ms linear;
-moz-transition: all 200ms linear;
-ms-transition: all 200ms linear;
-o-transition: all 200ms linear;
transition: all 200ms linear;
}
.panel:hover {
opacity: 0.4;
}
我真的建议您使用hover。但如果没有,请尝试$(“.panel”).mouseover(hoverUnownedPT(event)).mouseout(stopHoveringUnownedPT(event));我非常喜欢这种使用Javascript的方法,开销小得多,而且不依赖于jQuery。@MFNODDY是的,它更紧凑
.panel {
-webkit-transition: all 200ms linear;
-moz-transition: all 200ms linear;
-ms-transition: all 200ms linear;
-o-transition: all 200ms linear;
transition: all 200ms linear;
}
.panel:hover {
opacity: 0.4;
}