在鼠标悬停时更改同一类元素的CSS,具体取决于每个元素的id
我正在尝试使用外部(非内联)JavaScript 代码来根据类和 id 处理多个元素。
我的目标是,如果一个元素属于某个类,当它悬停在它上面时,它的 CSS 将根据它的 id 名称而改变。
在这个例子中:
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
我的目标是得到这个:
我在这个方向思考了一些事情:
const pElements = document.querySelectorAll('.p-class');
for (let i = 0; i < pElements .length; i++) {
pElements[i].addEventListener('mouseover', function() {
pElements[i].style.color = `#${pElements[i].getAttribute('id')`;
});
}
但是,我对此比较陌生,我不知道上面的代码是否有效或如何正确触发它。
任何见解/建议将不胜感激!
回答
最简单的方法是避免使用id,而是使用 CSS 自定义属性,例如--hoverColor:
/*
The default styling for the element(s):
*/
.p-class {
color: #000;
background-color: silver;
}
/*
The styles for the :hover pseudo-class/interaction:
*/
.p-class:hover {
/* the var() retrieves the named custom-property from
the closest ancestor element upon which it's defined.
Here this is specified in the inline 'style'
attribute for the .p-class elements: */
color: var(--hoverColor);
}
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
但是,鉴于您在问题中发布的自己的代码可以相对轻松地工作,如下所示:
const pElements = document.querySelectorAll('.p-class'),
toggle = (event) => {
// retrieves the element node to which the event
// was bound:
const target = event.currentTarget;
// if the event is mouseenter (so the user is
// hovering over the element):
if (event.type === 'mouseenter') {
// we update the color of the element
// according to the color held in the 'id'
// attribute, using a template-string to
// interpolate that value into the string
// to form a valid hexadecimal colour:
target.style.color = `#${target.id}`;
} else {
// if the event is of any type other than
// mouseenter, we unset the colour by setting
// the colour to an empty string (an invalid
// value) causing the style-rule to be discarded:
target.style.color = '';
}
};
// using NodeList.prototype.forEach() to iterate over the
// NodeList using an Arrow function:
pElements.forEach(
// para is a reference to each of the element Nodes of
// the NodeList over which we're iterating:
(para) => {
// here we bind a named function to handle
// the mouseenter/mouseleave (hover/unhover)
// events; in order to avoid duplicating the
// anonymous function:
// to handle the mouseenter:
para.addEventListener('mouseenter', toggle);
// to handle the mouseleave:
para.addEventListener('mouseleave', toggle);
});
.p-class {
color: #000;
background-color: silver;
}
参考:
- CSS:
- CSS 自定义属性。
var().- JavaScript:
- 箭头函数。
document.querySelectorAll().EventTarget.addEventListener().NodeList.prototype.forEach().