简体   繁体   English

为什么点击事件后悬停停止工作?

[英]Why does hover stop working after click event?

For some reason the hover pseudo selector stops working after the background gets changed.由于某种原因,悬停伪选择器在背景更改后停止工作。 I understand that this is caused because it creates two css rules for the background and the one caused by the jquery click overrides the hover one.我知道这是因为它为背景创建了两个 css 规则,而由 jquery 单击引起的一个覆盖了悬停规则。 Despite knowing the cause... I'm not sure how to fix this.尽管知道原因......我不知道如何解决这个问题。 Does anyone know how to workaround this?有谁知道如何解决这个问题? Thanks!谢谢!

HTML HTML

<nav class="top">
    <a class="ajaxAnchor" href="home.html">
        <button id="navOne" class="top">
            <span class="top">Home</span>
        </button>
    </a>
    <a class="ajaxAnchor" href="repair.html">
        <button id="navTwo" class="top">
            <span class="top">Repairs</span>
        </button>
    </a>
    <a class="ajaxAnchor" href="training.html">
        <button id="navFour" class="top">
            <span class="top">Training</span>
        </button>
    </a>
    <a class="ajaxAnchor" href="products.html">
        <button id="navThree" class="top">
            <span  class="top">Products</span>
        </button>
    </a>
    <a class="ajaxAnchor" href="about.html">
        <button id="navFive" class="top">
            <span class="top">About</span>
        </button>
    </a>
</nav>

CSS CSS

.top button:hover{
    background: #000000;
}

JavaScript JavaScript

$('.ajaxAnchor').on('click', function (event){ 
    event.preventDefault(); 
    $('a .top').css({'background' : 'transparent'});
    $('a .top').children().css({'background' : 'transparent'});
    $(this).children().css({'background' : '#EEEEEE'});
    var url = $(this).attr('href');
    $.get(url, function(data) {
        $('section.center').html(data);
    });
});

Fiddle小提琴

You can add a class to the active element instead of setting the style directly.您可以为活动元素添加一个类,而不是直接设置样式。

Script:脚本:

$('.ajaxAnchor').on('click', function (event){ 
    event.preventDefault(); 
    $('.ajaxAnchor').removeClass('active');
    $(this).addClass('active');
    var url = $(this).attr('href');
    $.get(url, function(data) {
        $('section.center').html(data);
    });
});

CSS: CSS:

.top button:hover, .active .top button:hover{
  background: #000;
}
.active .top button {
  background: #eee;
}

您正在使用 jquery 更改背景,因此其更改的标签样式属性您的 css 无法覆盖它,因此您可以使用!important或者您可以使用 javascript 进行悬停事件。

Just add important tag to your hover effect.只需为您的悬停效果添加重要标签即可。

.top button:hover{
    background: #000000!important;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM