转换后触发css悬停状态更改

时间:2022-11-05 23:02:04

I've got some UI that has javascript events that cause CSS changes that reposition elements in the UI. I'm having a problem with hover states, where the hover state doesn't update properly after these changes. I've boiled down a very simple example here.

我有一些UI有javascript事件导致CSS更改,重新定位UI中的元素。我遇到了悬停状态的问题,其中悬停状态在这些更改后没有正确更新。我在这里简单介绍了一个非常简单的例子。

  1. hover "block 1" Observe: "block one" turns blue
  2. 悬停“块1”观察:“块1”变为蓝色

  3. click "block 1" Observe: css changes cause the blocks to flip
  4. 单击“块1”观察:css更改导致块翻转

  5. Observe: the mouse is now hovering "block 2" but "block 1" is still blue
  6. 观察:鼠标现在悬停在“块2”,但“块1”仍然是蓝色

  7. Expected behavior: "block 2" should be blue after the transform and "block 1" should be red.
  8. 预期行为:变换后“块2”应为蓝色,“块1”应为红色。

  9. Observe: Moving the mouse very slightly causes them to "correct"
  10. 观察:略微移动鼠标会导致它们“纠正”

$(function() {
    $('.block').click(function () {
       $('.container').toggleClass('flipped'); 
    });
});
.container {
    display: flex;
    width: 150px;
}

.container.flipped {
     transform: rotate(180deg);    
}

.block {
    height: 50px;
    width: 50px;
    background-color: red;
    margin: 10px;
}

.block:hover {
    background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <div class="block">
        block 1
    </div>
    <div class="block">
        block 2
    </div>
</div>

Is there a way to ensure that the hover state gets updated properly after classes are applied and changes occur?

有没有办法确保在应用类并发生更改后正确更新悬停状态?

1 个解决方案

#1


1  

This solution is a bit of a hack. It doesn't work perfectly, but it gets the job done.

这个解决方案有点像黑客。它不能很好地工作,但它完成了工作。

$(function() {
    $('.block').click(function () {
       $('.container').hide();
       $('.container').toggleClass('flipped');
       $('.container').show(0);
    });
});

Hiding the container, flipping it and then showing it again forces that portion of the page to be redrawn, which seems to trigger the :hover selector again.

隐藏容器,翻转然后再显示它会强制重绘页面的这一部分,这似乎再次触发:悬停选择器。

Note: Passing 0 for the duration to show() seems to be necessary for this to work.

注意:传递0持续显示show()似乎是必要的。

Here's a demo:

这是一个演示:

CodePen Link

#1


1  

This solution is a bit of a hack. It doesn't work perfectly, but it gets the job done.

这个解决方案有点像黑客。它不能很好地工作,但它完成了工作。

$(function() {
    $('.block').click(function () {
       $('.container').hide();
       $('.container').toggleClass('flipped');
       $('.container').show(0);
    });
});

Hiding the container, flipping it and then showing it again forces that portion of the page to be redrawn, which seems to trigger the :hover selector again.

隐藏容器,翻转然后再显示它会强制重绘页面的这一部分,这似乎再次触发:悬停选择器。

Note: Passing 0 for the duration to show() seems to be necessary for this to work.

注意:传递0持续显示show()似乎是必要的。

Here's a demo:

这是一个演示:

CodePen Link