簡體   English   中英

更改:使用 JavaScript 懸停 CSS 屬性

[英]Change :hover CSS properties with JavaScript

JavaScript 如何改變 CSS :hover屬性?

例如:

HTML

<table>
  <tr>
    <td>Hover 1</td>
    <td>Hover 2</td>
  </tr>
</table>

CSS

table td:hover {
background:#ff0000;
}

如何使用 JavaScript 將td:hover屬性修改為background:#00ff00 我知道我可以使用 JavaScript 訪問樣式背景屬性:

document.getElementsByTagName("td").style.background="#00ff00";

但我不知道.style JavaScript 等效於:hover

:hover這樣的偽類從不引用元素,而是引用任何滿足樣式表規則條件的元素。 您需要編輯樣式表規則追加新規則或添加包含新:hover規則的新樣式表。

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);

不能通過Javascript 更改或更改實際的:hover選擇器。 但是,您可以使用mouseenter更改樣式,並在mouseleave上恢復(感謝@Bryan)。

您可以做的是更改對象的類並定義具有不同懸停屬性的兩個類。 例如:

.stategood_enabled:hover  { background-color:green}
.stategood_enabled        { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled       { background-color:black}

我在上面找到了這個: Change an element's class with JavaScript

function changeClass(object,oldClass,newClass)
{
    // remove:
    //object.className = object.className.replace( /(?:^|\s)oldClass(?!\S)/g , '' );
    // replace:
    var regExp = new RegExp('(?:^|\\s)' + oldClass + '(?!\\S)', 'g');
    object.className = object.className.replace( regExp , newClass );
    // add
    //object.className += " "+newClass;
}

changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");

很抱歉找到這個頁面 7 年太晚了,但這里有一個更簡單的方法來解決這個問題(任意改變懸停樣式):

HTML:

<button id=Button>Button Title</button>

CSS:

.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}

JavaScript:

var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');

很老的問題,所以我想我會添加一個更現代的答案。 現在 CSS 變量得到了廣泛的支持,它們可以用來實現這一點,而不需要 JS 事件或!important

以OP為例:

<table>
  <tr>
    <td>Hover 1</td>
    <td>Hover 2</td>
  </tr>
</table>

我們現在可以在 CSS 中執行此操作:

table td:hover {
  // fallback in case we need to support older/non-supported browsers (IE, Opera mini)
  background: #ff0000;
  background: var(--td-background-color);
}

並使用 javascript 添加懸停狀態,如下所示:

const tds = document.querySelectorAll('td');
tds.forEach((td) => {
  td.style.setProperty('--td-background-color', '#00ff00');
});

這是一個工作示例https://codepen.io/ybentz/pen/RwPoeqb

如果它符合您的目的,您可以在不使用 css 並在 javascript 中使用onmouseover事件的情況下添加懸停功能

這是一個代碼片段

<div id="mydiv">foo</div>

<script>
document.getElementById("mydiv").onmouseover = function() 
{
    this.style.backgroundColor = "blue";
}
</script>

您可以使用鼠標事件進行控制,例如懸停。 例如,以下代碼在您懸停該元素時可見。

var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
   foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
   foo.style.display="none";
})

這實際上並不是將 CSS 添加到單元格中,但會產生相同的效果。 雖然提供與上述其他版本相同的結果,但這個版本對我來說更直觀一點,但我是新手,所以值得一試:

$(".hoverCell").bind('mouseover', function() {
    var old_color = $(this).css("background-color");
    $(this)[0].style.backgroundColor = '#ffff00';

    $(".hoverCell").bind('mouseout', function () {
        $(this)[0].style.backgroundColor = old_color;
    });
});

這需要將要突出顯示的每個單元格的類設置為“hoverCell”。

當您檢測到該設備支持觸摸時,我建議將所有:hover屬性替換為:active 當你這樣做時只需調用這個函數touch()

   function touch() {
      if ('ontouchstart' in document.documentElement) {
        for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
          var sheet = document.styleSheets[sheetI];
          if (sheet.cssRules) {
            for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
              var rule = sheet.cssRules[ruleI];

              if (rule.selectorText) {
                rule.selectorText = rule.selectorText.replace(':hover', ':active');
              }
            }
          }
        }
      }
    }

我曾經有過這種需求,並為此創建了一個小型庫,用於維護 CSS 文檔

https://github.com/terotests/css

有了這個你可以說

css().bind("TD:hover", {
        "background" : "00ff00"
    });

它使用上面提到的技術,並嘗試處理跨瀏覽器問題。 如果由於某種原因存在像 IE9 這樣的舊瀏覽器,它將限制 STYLE 標簽的數量,因為舊的 IE 瀏覽器對頁面上可用的 STYLE 標簽數量有這個奇怪的限制。

此外,它通過僅定期更新標簽來限制標簽​​的流量。 對創建動畫類的支持也有限。

聲明一個全局變量:

var td

然后選擇您的 guiena pig <td>通過其id獲取它,如果您想更改所有這些,那么

window.onload = function () {
  td = document.getElementsByTagName("td"); 
}

制作一個要觸發的函數和一個循環來更改所有您想要的td

function trigger() {
    for(var x = 0; x < td.length; x++) { 
      td[x].className = "yournewclass"; 
    }
}

轉到您的 CSS 表:

.yournewclass:hover { background-color: #00ff00; }

就是這樣,有了這個,你可以讓你所有的<td>標簽獲得background-color: #00ff00; 通過直接更改其 css 屬性(在 css 類之間切換)懸停時。

有一些相同的問題,使用 addEventListener 事件“mouseenter”,“mouseleave”:

let DOMelement = document.querySelector('CSS selector for your HTML element');

// if you want to change e.g color: 
let origColorStyle = DOMelement.style.color;

DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });

DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })

或者當光標位於 DOM 元素上方時的其他樣式。 可以通過多種方式選擇 DOMElement。

您可以制作一個 CSS 變量,然后在 JS 中更改它。

:root {
  --variableName: (variableValue);
}

為了在 JS 中改變它,我做了這些方便的小功能:

var cssVarGet = function(name) {
  return getComputedStyle(document.documentElement).getPropertyValue(name);
};

var cssVarSet = function(name, val) {
  document.documentElement.style.setProperty(name, val);
};

您可以根據需要創建任意數量的 CSS 變量,並且我沒有發現函數中的任何錯誤; 之后,您所要做的就是將它嵌入到您的 CSS 中:

table td:hover {
  background: var(--variableName);
}

然后是 bam,一個只需要一些 CSS 和 2 個 JS 函數的解決方案!

我正在研究懸停,以便能夠在按鈕標簽中實現它們並制作懸停效果

 <button type="submit" style=" background-color:cornflowerblue; padding:7px; border-radius:6px" onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'" onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'" @click="form1()"> Login </button>

你可以在css中創建一個類

.hover:hover {
    background: #ff0000;
}

然后動態添加

const columns = document.querySelectorAll('table td');

for (let i = 0; i < columns.length; i++) {
   columns[i].classList.add('hover');
}

但是你的 css 和 js 文件應該在 index.html 中連接

對於我自己,我找到了以下選項:來自https://stackoverflow.com/a/70557483/18862444

 const el = document.getElementById('elementId'); el.style.setProperty('--focusHeight', newFocusHeight); el.style.setProperty('--focusWidth', newFocusWidth);
 .my-class { --focusHeight: 32px; --focusWidth: 256px; } .my-class:focus { height: var(--focusHeight); width: var(--focusWidth); }

    const tds = document.querySelectorAll('td');
    tds.forEach((td,index) => {
      td.addEventListener("mouseover", ()=>hover(index))
      td.addEventListener("mouseout", ()=>normal(index))
    });
    function hover(index){
      tds[index].style.background="red";
    }
    function normal(index){
      tds[index].style.background="yellow";
    }

試試這個代碼,它會工作正常。

如果您使用輕量級 html ux lang,請在此處查看示例,請編寫:

div root
 .onmouseover = ev => {root.style.backgroundColor='red'}
 .onmouseleave = ev => {root.style.backgroundColor='initial'}

上面的代碼執行 css :hover 元標記。

這個對我有用

        const useStyles = makeStyles({
        mystyle:{
            color: "red",
            FontFace: "oblique"
        },
        yourStyle:{
            backgroundColor:"green",
            border:0,
            color: 'white',
            "&:hover":{
                backgroundColor:"skyblue",
                border:0,
            }    
        },
        
         })

暫無
暫無

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

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