【问题标题】:CSS Hover Effect not working when an inline style is set设置内联样式时 CSS 悬停效果不起作用
【发布时间】:2018-07-27 12:31:30
【问题描述】:

我有一个 H1 元素,标准颜色为白色。这个元素在我的上部导航栏中。当页面滚动时,导航栏的背景颜色会发生变化,文本的颜色也会发生变化。因此文本颜色从 white 变为 black。为了实现这一点,我的 javascript 只是将一个内联样式标签添加到设置 color:black 的元素中。

还定义了一个悬停状态。当用户将鼠标悬停在 H1 元素上时,颜色变为深橙色。由于内联样式标签被设置为黑色,当鼠标悬停在其上时设置的颜色的 CSS 属性将被忽略,更好的说法是内联样式位于 CSS 属性之上。

我该如何解决这个问题?

let h1children = document.getElementById('divNavigationContainer').getElementsByTagName('h1'); let achildren = document.getElementById('divNavigationContainer').getElementsByTagName('a');

        if (window.scrollY) {
            document.getElementById('divNavigationContainer').style.backgroundColor = 'white';
            document.getElementById('divNavigationContainer').style.borderBottom = '1px solid darkorange';

            for(let i=0;i<h1children.length;i++) {
                h1children[i].style.color = 'black';
            }
            for(let i=0;i<achildren.length;i++) {
                achildren[i].style.color = 'black';
            }
        } else {
            document.getElementById('divNavigationContainer').style.backgroundColor = 'transparent';
            document.getElementById('divNavigationContainer').style.borderBottom = 'none';

            for(let i=0;i<h1children.length;i++) {
                h1children[i].style.color = 'white';
            }
            for(let i=0;i<achildren.length;i++) {
                achildren[i].style.color = 'white';
            }
        }

CSS:

    .aNavigationObjectText:hover {
        color:darkorange;
     }

    .aNavigationObjectText {
       float: right;
       position: relative;
       cursor: pointer;
       font-family: Arial;
       font-weight: unset;
       font-size: 15px;
       color: white;
       margin-left: 15px;
       margin-right: 15px;
       margin-top: 20px;
       text-decoration: none;
       transition: color .2s ease-in-out;
     }

编辑

我的问题被一个简单的 !important 标签解决了!

     .aNavigationObjectText:hover {
        color:darkorange !important;
     }

【问题讨论】:

  • 你能贴出你的css代码吗?
  • 使用!important
  • 您能否举例说明正在发生的事情、您所期待的以及您尝试过的事情
  • 是的 ^ 只有 !important 在 css 中悬停值后可以救你
  • 我已经编辑了问题!到目前为止,感谢您的帮助,我认为!important 是关键,是的,我现在就试试 :)

标签: javascript css colors hover


【解决方案1】:

!important 有效。请使用!important!您可以在网上搜索一长串原因。

此外,混合内联 CSS 和常规 CSS 也不是一个好主意。我的建议是将 CSS 类应用于元素:

document.getElementById("MyElement").className = "MyClass";

如果你这样做,那么你的悬停样式将在没有 !important 的情况下工作。

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 2018-11-25
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多