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

发布于 2025-01-22 09:10:47 字数 1380 浏览 1 评论 0原文

我想确保当跨度元素变成石灰时,出现一个警报框,但是,我尝试使用hasattribute()和getAttribute()尝试使if语句正常工作,但两者都对我不起作用,由于InnerHTML是因为在foreach()函数中配置,因此可能发生错误。

到目前为止,当我单击“绝对”单词输入时,将“绝对”放在Div框中时,Div框变绿色,但没有出现警报。

请帮忙!先感谢您。链接到所有代码行的链接,以防万一,对不起,这可能有点混乱,我有很多索洛尔恩的代码: 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");

};

I want to make sure that when the span element turns lime, an alert box shows up, however, I tried using both hasAttribute() and getAttribute() to try to make the if statement function properly, but both did not work for me, the error may be occurring because the innerHTML is because configured in a forEach() function.

So far, when I click enter with the word "Absolute" put in the div boxes, the div boxes turn green, but no alert shows up.

Please help! Thank you in advance. Link to all lines of code just in case, sorry it may be a bit messy, I have a lot of code for a 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");

};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浊酒尽余欢 2025-01-29 09:10:47

从上面的评论...

“我遇到的第一个问题是,OP是否控制了代码。如果这样,就无需根据UI更改做出其他操作。相反,状态更改应触发UI更改因此,另一种更改。 自定义事件 statechange 在处理封闭式(第三方)代码的情况下,仍然有可能使用

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>

mutation> mutation> mutation observer方法对于代码,一个人不拥有,因此无法更改/适应一个需求...

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>

From the above comment ...

"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"

The CustomEvent approach for code one does own and is allowed to change, and where decoupling makes sense ...

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>

The MutationObserver approach for code one does not own and thus can not change/adapt to ones needs ...

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>

帅气称霸 2025-01-29 09:10:47

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。

另一个选项是重组应用程序,以便根据用户交互触发事件,而这些事件相同的事件设置了给定元素的类(或颜色)。

There isn't a native CSS event in JavaScript.
The only option here is to periodically check the color.

For example:


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);

Pitfalls

However, for this to work, you must know the exact color you're looking for, and specify it in the right format. You'll also need to add your own checks to ensure the element is found, and the CSS property is found, to prevent an error. Don't forget to also clear the setInterval when you're finished with it. Also keep in mind, that the user can manually change the color of the element, and then trigger your event.

Alternative

Using a frontend framework, like React or Vue would make the exercise significantly easier. You could manage the element's color with a data attribute, then just watch that attribute for changes without the need for setInterval.

Another option would be restructuring the app, so that events are triggered based on a user interaction, and those same events set the class (or color) of a given element.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文