本文介绍了CSS:如何伪造 :hover 状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里,我有几个 div.当鼠标悬停它们时,会有过渡效果.(如左内角)

我想先假装一个悬停.例如,首先使左外角 div 处于 :hover 状态,而无需用户实际悬停操作.然后,当用户真正将鼠标悬停在其他 div 上时,假悬停状态被取消.

对于 HTML &CSS:

 

<!--内容-->

<div class="story"><!--内容-->

<div class="story"><!--内容-->

.故事{背景:无重复滚动 0 0 #2A2A2A;&:悬停{过渡:所有 0.25 秒的缓入缓出 0;背景:无重复滚动 0 0 变亮(#2A2A2A,20%);}}

我想做什么:

开始时,div#target 被强制进入 :hover 状态(所以它有不同的背景).之后,当用户开始使用鼠标悬停到其他 div 时,其他 div 变为 :hover 状态,div#target 回到正常状态.

当我们使用输入字段时,它很像 autofocus

更新:我想在有人进入此页面时立即触发元素的悬停状态.

jQuery:自动触发悬停

解决方案

您可以像这样向 :hover CSS 规则添加类声明:

.story:hover,.story.hover {过渡:所有 0.25 秒的缓入缓出 0;背景:无重复滚动 0 0 变亮(#2A2A2A,20%);}

现在您可以使用 JS 向 .story 元素添加类来模拟悬停效果:

$(document).on("ready", function () {$(".story").eq(0).addClass('hover');});

这会将悬停效果添加到文档就绪时的第一个 .story 元素.

这是一个演示:http://jsfiddle.net/fKupb/

我建议使用这种方法,因为它与 CSS 配合得很好.如果您为 mouseentermouseleave 设置了事件处理程序,那么您可以使用 JS 使用 jQuery 的 .trigger() 函数来触发这些事件处理程序:$(".story").eq(0).trigger('mouseenter');

Here, I have several divs. When mouse hover them, there would be a transition effect. (like the left-inner corner)

I want to fake a hover at first. For example, make the left-outer corner div in :hover state at first, without user's actual hover action. And then, when user really hovers over other divs, the fake hover state cancelled.

For HTML & CSS:

    <div class="story" id="target">
      <!--content-->
    </div>
    <div class="story">
      <!--content-->
    </div>
    <div class="story">
      <!--content-->
    </div>

.story{
  background: none repeat scroll 0 0 #2A2A2A;
  &:hover{
    transition: all 0.25s ease-in-out 0s;
    background: none repeat scroll 0 0 lighten(#2A2A2A, 20%);
  }
}

What I want to do:

At start, the div#target is forced into :hover state(So it has a different background). Later, when the user starts to use his mouse and hover to other divs, other divs changes into :hover state, and the div#target go back to normal state.

It's pretty much like a autofocus when we using input field

UPDATES:I want to trigger hover state of an element as soon as someone enters this page.

jQuery: Automatically trigger hover

解决方案

You can add a class declaration to your :hover CSS rule like this:

.story:hover,
.story.hover {
    transition: all 0.25s ease-in-out 0s;
    background: none repeat scroll 0 0 lighten(#2A2A2A, 20%);
}

And now you can use JS to add classes to the .story elements to mimic the hover effect:

$(document).on("ready", function () {
    $(".story").eq(0).addClass('hover');
});

This will add the hover effect to the first .story element on document-ready.

Here is a demo: http://jsfiddle.net/fKupb/

I suggest using this method because it plays nice with CSS. If you have an event handler setup for mouseenter and mouseleave then you can use JS to trigger those event handlers using jQuery's .trigger() function: $(".story").eq(0).trigger('mouseenter');

这篇关于CSS:如何伪造 :hover 状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:53
查看更多