简体   繁体   English

更改:使用 JavaScript 悬停 CSS 属性

[英]Change :hover CSS properties with JavaScript

How can JavaScript change CSS :hover properties? JavaScript 如何改变 CSS :hover属性?

For example:例如:

HTML HTML

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

CSS CSS

table td:hover {
background:#ff0000;
}

How can the td:hover properties be modified to, say, background:#00ff00 , with JavaScript?如何使用 JavaScript 将td:hover属性修改为background:#00ff00 I know I could access the style background property using JavaScript with:我知道我可以使用 JavaScript 访问样式背景属性:

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

But I don't know of a .style JavaScript equivalent for :hover .但我不知道.style JavaScript 等效于:hover

Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule.:hover这样的伪类从不引用元素,而是引用任何满足样式表规则条件的元素。 You need to edit the stylesheet rule , append a new rule , or add a new stylesheet that includes the new :hover rule.您需要编辑样式表规则追加新规则或添加包含新: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);

You can't change or alter the actual :hover selector through Javascript.不能通过Javascript 更改或更改实际的:hover选择器。 You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).但是,您可以使用mouseenter更改样式,并在mouseleave上恢复(感谢@Bryan)。

What you can do is change the class of your object and define two classes with different hover properties.您可以做的是更改对象的类并定义具有不同悬停属性的两个类。 For example:例如:

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

And this I found on: Change an element's class with JavaScript我在上面找到了这个: 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");

Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):很抱歉找到这个页面 7 年太晚了,但这里有一个更简单的方法来解决这个问题(任意改变悬停样式):

HTML: HTML:

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

CSS: CSS:

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

JavaScript: 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');

Pretty old question so I figured I'll add a more modern answer.很老的问题,所以我想我会添加一个更现代的答案。 Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important .现在 CSS 变量得到了广泛的支持,它们可以用来实现这一点,而不需要 JS 事件或!important

Taking the OP's example:以OP为例:

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

We can now do this in the CSS:我们现在可以在 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);
}

And add the hover state using javascript like so:并使用 javascript 添加悬停状态,如下所示:

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

Here's a working example https://codepen.io/ybentz/pen/RwPoeqb这是一个工作示例https://codepen.io/ybentz/pen/RwPoeqb

If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript如果它符合您的目的,您可以在不使用 css 并在 javascript 中使用onmouseover事件的情况下添加悬停功能

Here is a code snippet这是一个代码片段

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

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

You can use mouse events to control like hover.您可以使用鼠标事件进行控制,例如悬停。 For example, the following code is making visible when you hover that element.例如,以下代码在您悬停该元素时可见。

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

This is not actually adding the CSS to the cell, but gives the same effect.这实际上并不是将 CSS 添加到单元格中,但会产生相同的效果。 While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:虽然提供与上述其他版本相同的结果,但这个版本对我来说更直观一点,但我是新手,所以值得一试:

$(".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;
    });
});

This requires setting the Class for each of the cells you want to highlight to "hoverCell".这需要将要突出显示的每个单元格的类设置为“hoverCell”。

I'd recommend to replace all :hover properties to :active when you detect that device supports touch.当您检测到该设备支持触摸时,我建议将所有:hover属性替换为:active Just call this function when you do so as touch()当你这样做时只需调用这个函数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');
              }
            }
          }
        }
      }
    }

I had this need once and created a small library for, which maintains the CSS documents我曾经有过这种需求,并为此创建了一个小型库,用于维护 CSS 文档

https://github.com/terotests/css https://github.com/terotests/css

With that you can state有了这个你可以说

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

It uses the techniques mentioned above and also tries to take care of the cross-browser issues.它使用上面提到的技术,并尝试处理跨浏览器问题。 If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.如果由于某种原因存在像 IE9 这样的旧浏览器,它将限制 STYLE 标签的数量,因为旧的 IE 浏览器对页面上可用的 STYLE 标签数量有这个奇怪的限制。

Also, it limits the traffic to the tags by updating tags only periodically.此外,它通过仅定期更新标签来限制标签​​的流量。 There is also a limited support for creating animation classes.对创建动画类的支持也有限。

Declare a global var:声明一个全局变量:

var td

Then select your guiena pig <td> getting it by its id , if you want to change all of them then然后选择您的 guiena pig <td>通过其id获取它,如果您想更改所有这些,那么

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

Make a function to be triggered and a loop to change all of your desired td 's制作一个要触发的函数和一个循环来更改所有您想要的td

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

Go to your CSS Sheet:转到您的 CSS 表:

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

And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00;就是这样,有了这个,你可以让你所有的<td>标签获得background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).通过直接更改其 css 属性(在 css 类之间切换)悬停时。

Had some same problems, used addEventListener for events "mousenter", "mouseleave":有一些相同的问题,使用 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 })

Or something else for style when cursor is above the DOMelement.或者当光标位于 DOM 元素上方时的其他样式。 DOMElement can be chosen by various ways.可以通过多种方式选择 DOMElement。

You can make a CSS variable, and then change it in JS.您可以制作一个 CSS 变量,然后在 JS 中更改它。

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

to change it in JS, I made these handy little functions:为了在 JS 中改变它,我做了这些方便的小功能:

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

and

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

You can make as many CSS variables as you want, and I haven't found any bugs in the functions;您可以根据需要创建任意数量的 CSS 变量,并且我没有发现函数中的任何错误; After that, all you have to do is embed it in your CSS:之后,您所要做的就是将它嵌入到您的 CSS 中:

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

And then bam, a solution that just requires some CSS and 2 JS functions!然后是 bam,一个只需要一些 CSS 和 2 个 JS 函数的解决方案!

I was researching about hover, to be able to implement them in the button label and make the hover effect我正在研究悬停,以便能够在按钮标签中实现它们并制作悬停效果

 <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>

You can create a class in css你可以在css中创建一个类

.hover:hover {
    background: #ff0000;
}

and then add it dynamically然后动态添加

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

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

But your css and js files should be connected in index.html但是你的 css 和 js 文件应该在 index.html 中连接

For myself, I found the following option: from https://stackoverflow.com/a/70557483/18862444对于我自己,我找到了以下选项:来自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";
    }

Try this code it will work fine.试试这个代码,它会工作正常。

If you use lightweight html ux lang, check here an example , write:如果您使用轻量级 html ux lang,请在此处查看示例,请编写:

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

The code above performes the css :hover metatag.上面的代码执行 css :hover 元标记。

This one worked for me这个对我有用

        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