使用jQuery Hover更改css样式

Hel*_*ore 1 javascript css jquery

我想在悬停进出时更改按钮的背景颜色.请帮助我使我的jquery代码工作.

function onHoverIn(button) {
    $(button).css('background-color', 'rgba(193, 86, 10, 0.86)')
};
function onHoverOut(button) {
    $(button).css('background-color', 'rgba(26, 13, 3, 0.26)')
};
$("button").hover(onHoverIn(this), onHoverOut(this));
Run Code Online (Sandbox Code Playgroud)

参考 - https://api.jquery.com/hover/

Rok*_*jan 5

回调hover()函数已经是this(jQuery元素对象引用)的好朋友,所以你需要的只是撤销$(this)

function onHoverIn() {
   $(this).css('background-color', 'rgba(193, 86, 10, 0.86)');
}
function onHoverOut() {
   $(this).css('background-color', 'rgba(26, 13, 3, 0.26)');
}
$("button").hover(onHoverIn, onHoverOut);
Run Code Online (Sandbox Code Playgroud)

您不能将参数传递给参数.这就是你的代码中的错误:

.method( myFunz( this ) )
//       ^argument  ^argument :( 
Run Code Online (Sandbox Code Playgroud)

这怎么$(this)是那些可命名函数声明

jQuery .hover()文档

.hover(handlerIn,handlerOut)

handlerIn
类型:Function(Event eventObject)
鼠标指针进入元素时执行的函数.

handlerOut
类型:Function(Event eventObject)
当鼠标指针离开元素时执行的函数.

所以.hover()方法接受两个函数回调.

并探索该.hover()方法的jQuery代码:

hover: function( fnOver, fnOut ) {
    return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
Run Code Online (Sandbox Code Playgroud)

你可以清楚地看到,它returnŠ this(的Event eventObject)保持方法chainability( .hover().click().etc()),并为您访问的this(Event eventObject)谁触发事件.


如果(真的,如果)你需要的只是一个:hover改变了background-color

使用CSS :)

button {
    background-color : rgba(193, 86, 10, 0.86);
}
button:hover {
    background-color : rgba(26, 13, 3, 0.26);
}
Run Code Online (Sandbox Code Playgroud)