如果跨度是某种颜色,是否有可能做某事?

Is it possible that if a span is a certain color do something?

我想确保当 span 元素变成石灰时,会出现一个警告框,但是,我尝试同时使用 hasAttribute() 和 getAttribute() 来尝试使 if 语句正常运行,但两者都没有对我不起作用,可能会发生错误,因为 innerHTML 是在 forEach() 函数中配置的。

到目前为止,当我单击输入并在 div 框中输入“绝对”一词时,div 框变为绿色,但没有显示任何警报。

请帮忙!先感谢您。 Link 所有代码行以防万一,抱歉可能有点乱,我有很多代码用于 sololearn:https://code.sololearn.com/WX59M6HHngc5

const pText = document.querySelector("#p123").innerText.toUpperCase()
const button = document.querySelector("#ENTER")

Array.from(document.querySelectorAll(".amot")).forEach(function(element) {

button.addEventListener("click", () => {
  const text = element.textContent.toUpperCase()

  if (text.match(/\d/gi) || text.length < 1 || text.match(/[^a-z]/gi)) {
    element.innerText = text
    return
  }

  element.innerHTML = ""
  text.split("").forEach((letter, i) => {
    if (pText.includes(letter) && pText[i] === letter) {
      element.innerHTML += `<span id = "span1" style="color: lime">${letter}</span>`
    } else if (pText.includes(letter)){
      element.innerHTML += `<span style="color: orange">${letter}</span>`
    } else {
      element.innerHTML += `<span style="color: lightgrey">${letter}</span>`
    }
  })
})

let sp1 = document.getElementById("span1");

if(sp1.hasAttribute('style') == "color: lime") {

alert("Test");

};

JavaScript 中没有原生 CSS 事件。 这里唯一的选择是定期检查颜色。

例如:


const targetColor = '#ff0000';
const elementId = 'my-elem';

const checkColor = () => {
  const myElem = document.getElementById(elementId);
  const color = getComputedStyle(myElem).color;
  if (color && color.toLowerCase() === targetColor) {
    alert('Color has been changed.');
  }
}

setInterval(checkColor, 500);

陷阱

但是,要使其正常工作,您必须知道要查找的确切颜色,并以正确的格式指定它。您还需要添加自己的检查以确保找到元素,并找到 CSS 属性,以防止出错。完成后不要忘记清除 setInterval。还要记住,用户可以手动更改元素的颜色,然后触发您的事件。

备选

使用 React 或 Vue 等前端框架会使练习变得更加容易。您可以使用数据属性管理元素的颜色,然后只需观察该属性的变化而无需 setInterval。

另一种选择是重组应用程序,以便根据用户交互触发事件,并且这些相同的事件设置给定元素的 class(或颜色)。

从上面的评论...

"The first question I have is, whether the OP is in control of the code. If so there is no need to make an additional action dependent on an UI change. Instead the state change should trigger the UI change and the additional change. Thus a possible clean approach was to dispatch a custom event on statechange. In case of dealing with closed (third party) code there is still the possibility of utilizing a MutationObserver"

代码一的 CustomEvent 方法确实拥有并允许更改,并且解耦有意义...

const elmNode = document.querySelector('p')

elmNode
  // listen to an own custom event.
  .addEventListener('uiapprovalchange', evt => {
    if (evt.detail.isApproved) {

      console.log('text color should have changed into an approval state');
      // console.log({ evt: { detail: evt.detail } });
    } else {
      // console.clear();
    }
    console.log({ evt: { detail: evt.detail } });
  });

elmNode
  .addEventListener('click', ({ currentTarget }) => {
    const { dataset } = currentTarget;
    const doApprove = (dataset.approved !== 'true');

    dataset.approved = String(doApprove);
    currentTarget.style.cssText = doApprove ? "color: lime" : '';

    // create and dispatch an own custom event.
    currentTarget.dispatchEvent(
      new CustomEvent('uiapprovalchange', {
        detail: {
          isApproved: doApprove,
        },
      }),
    );
  });
<p>click in order to toggle the <em>approved</em> color change</p>

代码一的 MutationObserver 方法不属于自己,因此不能 change/adapt 满足需求 ...

function handleMutation(recordList, observer) {
  recordList.forEach(({ type, target, attributeName }) => {
    if (
      // assure correct mutation.
      type === 'attributes' &&
      attributeName === 'style' &&
      target.matches('body > p')
    ) {
      // normalize css text value.
      const text = target.style.cssText.replace((/\s+/g), '');

      if (text.includes('color:lime')) {
        console.log('text color should have changed into an approval state');
      } else {
        console.clear();
      }
    }
  });
}
const targetNode = document.querySelector('p');
const options = { attributes: true };

const observer = new MutationObserver(handleMutation);
observer.observe(targetNode, options);

targetNode
  .addEventListener('click', ({ currentTarget }) => {
    const { dataset } = currentTarget;
    const doApprove = (dataset.approved !== 'true');

    dataset.approved = String(doApprove);
    currentTarget.style.cssText = doApprove ? "color: lime" : '';
  });
<p>click in order to toggle the <em>approved</em> color change</p>