通过 jQuery/Javascript 添加悬停 CSS 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13707134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:42:11  来源:igfitidea点击:

Adding hover CSS attributes via jQuery/Javascript

javascriptjqueryhtmlcsshover

提问by Nyxynyx

Some CSS styles need to be applied to an element on hover, and CSS styles have to be applied using javascript/jquery directly and not through stylesheets or $(this).addClass('someStyle')because I am injecting the DOM elements into another page.

某些 CSS 样式需要在悬停时应用于元素,并且必须直接使用 javascript/jquery 应用 CSS 样式,而不是通过样式表或$(this).addClass('someStyle')因为我将 DOM 元素注入另一个页面。

We can apply the usual css styles using

我们可以使用通常的 css 样式

$('#some-content').css({
    marginTop: '60px',
    display: 'inline-block'
});

How should we add the CSS styles for :hoverevents?

我们应该如何为:hover事件添加 CSS 样式?



Do we have to resort to:

我们是否必须求助于:

$('#some-content').hover(
       function(){ $(this).css('display', 'block') },
       function(){ $(this).css('display', 'none') }
)

采纳答案by Jon

I find using mouseenter and mouseleave to be better than hover. There's more control.

我发现使用 mouseenter 和 mouseleave 比悬停更好。有更多的控制权。

$("#somecontent").mouseenter(function() {
    $(this).css("background", "#F00").css("border-radius", "3px");
}).mouseleave(function() {
     $(this).css("background", "00F").css("border-radius", "0px");
});

回答by Mark Walters

Try this:

尝试这个:

$('#some-content').hover(function(){
    $(this).css({ marginTop: '60px', display: 'inline-block' });
}, function(){
    $(this).css({ //other stuff });
});

or using classes

或使用类

$('#some-content').hover(function(){
    $(this).toggleClass('newClass');
});

More info here .hover()and .toggleClass()

更多信息在这里.hover().toggleClass()

回答by Wouter J

You should put them in a hoverevent:

你应该把它们放在一个悬停事件中:

var elem = $('#elem');

elem.hover(function () {
    // ... :hover, set styles
}, function () {
    // ... this function is called when the mouse leaves the item, set back the
    //     normal styles
});

However, I completely recommend to put your CSS in classes and use those classes in JS, you should split the languages as much as you can.

但是,我完全建议将您的 CSS 放在类中并在 JS 中使用这些类,您应该尽可能多地拆分语言。

回答by Laz Karimov

$("#someObj").hover(function(){
    $(this).css(...);
}:);

http://api.jquery.com/hover/

http://api.jquery.com/hover/