簡體   English   中英

設置內聯樣式時,CSS 懸停效果不起作用

[英]CSS Hover Effect not working when an inline style is set

我有一個 H1 元素,它的標准顏色為白色。 這個元素在我的上部導航欄中。 當頁面滾動時,導航欄的背景顏色會發生變化,文本的顏色也會發生變化。 所以文本顏色從white變為black 為了實現這一點,我的 javascript 只是向設置color:black的元素添加了一個內聯樣式標簽。

還定義了懸停狀態。 當用戶將鼠標懸停在 H1 元素上時,顏色會更改為 darkorange 由於內聯樣式標簽被設置為黑色,當鼠標懸停在它上面時設置的顏色的 CSS 屬性被忽略,更好的說法是內聯樣式位於 CSS 屬性之上。

我怎么解決這個問題?

let h1children = document.getElementById('divNavigationContainer').getElementsByTagName('h1'); 讓 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 和常規 CSS 也不是一個好主意。 我的建議是將 CSS 類應用於元素:

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

如果您這樣做,那么您的懸停樣式將在沒有 !important 的情況下工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM