【问题标题】:Changing CSS of elements of the same class onmouseover, depending on each element's id在鼠标悬停时更改同一类元素的 CSS,具体取决于每个元素的 id
【发布时间】:2021-04-04 19:31:19
【问题描述】:

我正在尝试使用外部(非内联)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')`;
  });
}

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

任何见解/建议都将受到高度赞赏!

【问题讨论】:

  • 除了这一行末尾缺少},您的代码没问题。正确的代码是:pElements[i].style.color = `#${pElements[i].getAttribute('id')}`; 但是,依赖id 属性是有问题的,除非您可以保证每个 id 具有不同的值。你最好使用data attribute,比如data-color

标签: javascript html css


【解决方案1】:

最简单的方法是避免使用 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>

参考资料:

【讨论】:

    【解决方案2】:

    Array.from(document.querySelectorAll('.p-class')).forEach( p_element => {
      const OriginalColor = p_element.style.color;
      p_element.addEventListener("mouseenter", () => { p_element.style.color = '#' + p_element.id });
      p_element.addEventListener("mouseleave", () => { p_element.style.color = OriginalColor });
    });
    .p-class {
      background-color: lightgrey;
    }
    <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>

    【讨论】:

    • 谢谢! Array.from() 是必要的吗?据我了解,NodeList 也很好用(即document.querySelectorAll('.p-class').forEach(....);
    猜你喜欢
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多