使用 JavaScript 更改 :hover 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";
但我不知道:hover
有.style
JavaScript 等效物。
: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(。
一个很老的问题,所以我想我会添加一个更现代的答案。现在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
您可以做的是更改对象的类并定义两个具有不同悬停属性的类。例如:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
这是我在以下方面发现的:使用 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 的情况下添加悬停功能,并在 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";
})
我建议在检测到设备支持触摸时替换所有: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添加到单元格中,而是提供相同的效果。 虽然提供了与上面其他人相同的结果,但这个版本对我来说更直观一些,但我是一个新手,所以把它当作它的价值:
$(".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"。
您可以创建一个 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函数的解决方案!
我曾经有过这个需求,并创建了一个小型库,用于维护CSS文档
https://github.com/terotests/css
有了这个,你可以声明
css().bind("TD:hover", {
"background" : "00ff00"
});
它使用上述技术,并尝试解决跨浏览器问题。如果由于某种原因存在像IE9这样的旧浏览器,它将限制STYLE标签的数量,因为较旧的IE浏览器对页面上可用的STYLE标签数量有这种奇怪的限制。
此外,它通过仅定期更新标签来限制标签的流量。对创建动画类的支持也有限。
声明一个全局变量:
var td
然后选择您的豚鼠<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; }
就是这样,有了这个,您可以通过直接更改其 css 属性(在 css 类之间切换(使所有<td>
标签在悬停时获得background-color: #00ff00;
。
对于我自己,我找到了以下选项:从 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);
}
有一些相同的问题,将addEventListener用于事件"mousenter","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元素上方时的其他样式。圆顶可以通过多种方式进行选择。
我正在研究悬停,以便能够在按钮标签中实现它们并使悬停效果
<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>
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";
}
试试这段代码,它会正常工作。
你可以在 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文件应该在索引中连接.html
如果你使用轻量级的html ux lang,检查这里的例子,写:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
上面的代码执行 css :hover 元标记。
- 谷歌图表-如何更改整个表的css属性
- 将css属性替换为变量
- 使用Jquery/Javascript替换CSS属性
- 如何使用JavaScript查找未定义的CSS属性的值
- 在jquerymobile中设置按钮css属性的动画
- JavaScript无法提取引号css属性
- 使用AngularJS动态更改css属性
- 使用javascript获取具有特定CSS属性的所有元素
- 将css属性添加到对象的集合中
- 取消img的css属性宽度和高度(不能使用“auto”)
- CSS属性更改侦听器
- 如何更改与Backbone集合中的模型相关联的几个元素的css属性
- 如何使用java脚本或jQuery基于相同的特定css属性对元素进行分组
- 如何在不链接/jquery的情况下使用方法应用css属性数组
- 在 javascript css 属性中使用变量
- 在jQuery中链接时CSS属性不起作用
- jQuery检查CSS宽度是否大于0,然后添加CSS属性
- 使用循环增加css属性值
- 更改类所选空输入的CSS属性
- 无法查找元素'手动加载CSS文件时的CSS属性