簡體   English   中英

如果跨度是某種顏色,是否有可能做某事?

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

我想確保當 span 元素變成石灰時,會出現一個警告框,但是,我嘗試同時使用 hasAttribute() 和 getAttribute() 來嘗試正確地制作 if 語句 function,但兩者都對我不起作用,發生錯誤的原因可能是 innerHTML 是在 forEach() function 中配置的。

到目前為止,當我單擊輸入並在 div 框中輸入“絕對”一詞時,div 框變為綠色,但沒有顯示任何警報。

請幫忙。 預先感謝您,鏈接到所有代碼行以防萬一,抱歉可能有點亂:我有很多用於 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");

};

從上面的評論...

“我的第一個問題是,OP 是否控制代碼。如果是這樣,則無需根據 UI 更改進行額外操作。相反,state 更改應觸發 UI 更改和其他更改。因此一種可能的干凈方法是在statechange上調度自定義事件。在處理封閉(第三方)代碼的情況下,仍然可以利用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方法不擁有,因此不能改變/適應那些需要......

 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>

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(或顏色)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM