gpt4 book ai didi

javascript - 使用 jQuery Hover 更改 css 样式

转载 作者:行者123 更新时间:2023-11-30 08:34:01 24 4
gpt4 key购买 nike

我想在鼠标悬停时更改按钮的背景颜色。请帮助我使我的 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));

引用 - https://api.jquery.com/hover/

最佳答案

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

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);

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

.method( myFunz( this ) )
// ^argument ^argument :(

$(this) 如何在那些命名函数声明 中可用?

jQuery .hover() Docs

.hover( handlerIn, handlerOut )

handlerIn
Type: Function( Event eventObject )
A function to execute when the mouse pointer enters the element.

handlerOut
Type: Function( Event eventObject )
A function to execute when the mouse pointer leaves the element.

所以 .hover() 方法接受两个 function 回调。

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

hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},

您可以清楚地看到它返回this(Event eventObject)以保持方法的可链接性(.hover() .click().etc()) 并让您可以访问触发事件的 this (Event eventObject)。


If (really, if) 你只需要一个 :hover 来改变 background-color

使用 CSS :)

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

关于javascript - 使用 jQuery Hover 更改 css 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com