更改:使用JavaScript悬停CSS属性

时间:2022-11-05 12:44:33

I need to find a way to change CSS :hover properties using JavaScript.

我需要找到一种方法来改变CSS:使用JavaScript的悬停属性。

For example, suppose I have this HTML code:

例如,假设我有这个HTML代码:

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

And the following CSS code:

以下CSS代码:

table td:hover {
background:#ff0000;
}

I would like to use JavaScript to change the <td> hover properties to, say, background:#00ff00. know I could access the style background property using JavaScript as:

我想使用JavaScript将悬停属性更改为背景:#00ff00。知道我可以使用JavaScript访问样式背景属性:

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

But I don't know of a JavaScript equivalent for :hover. How do I change these <td>'s :hover background using JavaScript?

但是我不知道JavaScript的等价物:hover。如何更改这些:使用JavaScript悬停背景?

Your help is greatly appreciated!

非常感谢您的帮助!

8 个解决方案

#1


66  

Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.

伪类如:悬停从不引用元素,而是引用满足样式表规则条件的任何元素。您需要编辑样式表规则,附加新规则或添加包含new: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);

#2


27  

You can't change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).

您无法通过Javascript更改或更改实际:悬停选择器。但是,您可以使用mouseenter更改样式,然后恢复鼠标左键(感谢@Bryan)。

#3


7  

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

我发现:用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");

#4


3  

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>

#5


1  

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.

此外,它还通过定期更新标记来限制标记的流量。对创建动画类的支持也很有限。

#6


1  

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 通过它的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; when hovered by changing its css propriety directly (switching between css classes).

就是这样,通过它,您可以使所有标签获得背景颜色:#00ff00;通过直接改变其css的适当性(在css类之间切换)来盘旋。

#7


0  

This is not actually adding the CSS to the cell, but gives the same effect. 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:

这实际上并不是将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;
        });
});

This requires setting the Class for each of the cells you want to highlight to "hoverCell".

这需要为要突出显示的每个单元格设置Class为“hoverCell”。

#8


0  

I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()

我建议在检测到设备支持触摸时将所有:悬停属性替换为:active。只需在触摸时调用此函数()

   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');
              }
            }
          }
        }
      }
    }

#1


66  

Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.

伪类如:悬停从不引用元素,而是引用满足样式表规则条件的任何元素。您需要编辑样式表规则,附加新规则或添加包含new: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);

#2


27  

You can't change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).

您无法通过Javascript更改或更改实际:悬停选择器。但是,您可以使用mouseenter更改样式,然后恢复鼠标左键(感谢@Bryan)。

#3


7  

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

我发现:用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");

#4


3  

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>

#5


1  

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.

此外,它还通过定期更新标记来限制标记的流量。对创建动画类的支持也很有限。

#6


1  

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 通过它的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; when hovered by changing its css propriety directly (switching between css classes).

就是这样,通过它,您可以使所有标签获得背景颜色:#00ff00;通过直接改变其css的适当性(在css类之间切换)来盘旋。

#7


0  

This is not actually adding the CSS to the cell, but gives the same effect. 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:

这实际上并不是将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;
        });
});

This requires setting the Class for each of the cells you want to highlight to "hoverCell".

这需要为要突出显示的每个单元格设置Class为“hoverCell”。

#8


0  

I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()

我建议在检测到设备支持触摸时将所有:悬停属性替换为:active。只需在触摸时调用此函数()

   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');
              }
            }
          }
        }
      }
    }