首页 > 解决方案 > 在鼠标悬停时更改同一类元素的 CSS,具体取决于每个元素的 id

问题描述

我正在尝试使用外部(非内联)JavaScript 代码来处理多个元素,具体取决于它们的类和 id。

我的目标是,如果一个元素属于某个类,当它悬停在其上时,它的 CSS 将根据它的 id 名称而改变。

在这个例子中:

<p class="p-class" id="000">Hi</p>
<p class="p-class" id="FFF">Hi</p>
<p class="p-class" id="FFFF66">Hi</p>
<p class="p-class" id="498F83">Hi</p>

我的目标是得到这个:

<p class="p-class" id="000" style="color:#000">Hi</p>
<p class="p-class" id="FFF" style="color:#FFF">Hi</p>
<p class="p-class" id="FFFF66" style="color:#FFFF66">Hi</p>
<p class="p-class" id="498F83" style="color:#498F83">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')`;
  });
}

但是,我对此比较陌生,我不知道上面的代码是否有效或如何正确触发它。

任何见解/建议将不胜感激!

标签: javascripthtmlcss

解决方案


最简单的方法是避免使用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 class="p-class" style="--hoverColor: #000">Hi</p>
<p class="p-class" style="--hoverColor: #FFF">Hi</p>
<p class="p-class" style="--hoverColor: #FFFF66">Hi</p>
<p class="p-class" style="--hoverColor: #498F83">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;
}
<p class="p-class" id="000">Hi</p>
<p class="p-class" id="FFF">Hi</p>
<p class="p-class" id="FFFF66">Hi</p>
<p class="p-class" id="498F83">Hi</p>

参考:


推荐阅读