jquery将悬停元素传递给函数

时间:2014-08-11 20:16:47

标签: javascript jquery html css

我有很多关于html类“panel”的标签。当用户悬停选项卡时,不透明度变为0.4。当他们将鼠标移出标签时,不透明度变得正常。这是我的代码,但它不起作用。开发工具没有报告错误。它可能有一些事情要做传递给函数的悬停元素。在这种情况下,什么是“事件”和“$(this)”?

的index.html

        <div class="panel">
            text text text
        </div>
        <div class="panel ">
            text text text
        </div>

shared.js

    $(".panel").on("mouseover", hoverUnownedPT(event))
                                .on("mouseout", stopHoveringUnownedPT(event));


function hoverUnownedPT(e){
    $(this).css({
        "opacity": "0.4",
        "filter": "alpha(opacity:40)"
    });
}

function stopHoveringUnownedPT(e){
    $(this).css({
        "opacity": "1",
        "filter": "alpha(opacity:100)"
    });
}

3 个答案:

答案 0 :(得分:2)

正如另一个回答所提到的,你调用函数而不是将它们作为回调传递,省略()来传递实际的函数对象。

你想要的是:

$(".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'here

答案 1 :(得分:0)

您正在调用函数而不是将它们传递给.on()方法(并且您正在使用未声明的event变量)。试试这个:

$(".panel").on("mouseover", hoverUnownedPT)
           .on("mouseout", stopHoveringUnownedPT);

如果您使用strict mode,您的浏览器控制台可能至少会遇到代码中的一个问题。

答案 2 :(得分:0)

你可以简单地使用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;
}

Demo