javascript 用 js 触发 css:hover 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10680446/
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-10-26 10:40:29  来源:igfitidea点击:

Trigger the css:hover event with js

javascripthtmlcss

提问by lemon

I have <div class="animate">and in css:

<div class="animate">在 css 中:

div.animate:hover{
//do stuff
}

But would also like to invoke this via javascript.

但也想通过 javascript 调用它。

Is it possible?

是否可以?

采纳答案by evancohen

Instead of doing it this way, I suggest you just add a class to the other tag. In jQuery it would be:

我建议您不要这样做,而是向另一个标签添加一个类。在 jQuery 中,它将是:

 $(window).load(function() {
    $('.trigger-animate').hover(function(){
        $('.animate').addClass('hover');
    });
}

I'd recommend using this method, because it handles both onMouseOver and onMouseOut (this way you can also remove the class when your mouse leaves $('.trigger-animate') if you so desired using this syntax:

我建议使用这种方法,因为它同时处理 onMouseOver 和 onMouseOut(这样你也可以在你的鼠标离开 $('.trigger-animate') 时删除类,如果你愿意使用以下语法:

.hover( handlerIn(eventObject), handlerOut(eventObject) )
 checking out the documentation

回答by Meligy

As described in Trigger css hover with JSthis is not possible as-is (if you want it as described exactly at the time of the creation of this answer).

使用 JS 触发 css 悬停中所述,这是不可能的(如果您希望在创建此答案时准确描述它)。

But the main goal is achievable by:

但主要目标可以通过以下方式实现:

  1. Setting a class hover(or whatever name) as well as the selector :hoverin the CSS.
  2. Calling .addClass("hover")to trigger CSS, and .trigger("hover")or .trigger("mouseenter")to trigger the JS.
  3. Ensuring the mouseleavehandler. or 2nd .hover()handler, clears the hoverclass if present.
  1. 在 CSS 中设置类hover(或任何名称)以及选择器:hover
  2. 调用.addClass("hover")触发 CSS,.trigger("hover").trigger("mouseenter")触发 JS。
  3. 确保mouseleave处理程序。或第二个.hover()处理程序,hover如果存在则清除该类。