【问题标题】:Change aria attribute value using JavaScript Observer method使用 JavaScript Observer 方法更改 aria 属性值
【发布时间】:2021-02-12 03:34:16
【问题描述】:

谁能提供一个 HTML div 元素的示例,该元素具有 aria-highlight 属性,使用 JavaScript 观察者方法更改并通知元素?一个例子是使用一个复选框来切换 div 并更改 div 元素的背景。我需要在 vanilla JavaScript 中完成此操作

示例 HTML

<div id="mydiv" aria-highlight="false" style="background: red; height: 100px; width: 100px"></div>
<label for="highlight"><input type="checkbox id="highlight">Highlight Div</label>

【问题讨论】:

  • 没有“JavaScript 观察者方法”。浏览器 DOM 中有几种不同的类型实现了观察者模式,比如答案中提到的 MutationObserver 或 IntersectionObserver 类型。请更具体地说明您在说什么。
  • 这能回答你的问题吗? JavaScript: Listen for attribute change?

标签: javascript html css


【解决方案1】:

下面,您有一个带有事件处理程序的复选框来切换aria-highlight 值。

还有一个观察者,它触发 div 的属性更改。

// Our two elements
let square = document.querySelector("#mydiv")
let chk = document.querySelector("#highlight")

// Checkbox click handler
chk.addEventListener("click", function(){
  square.setAttribute("aria-highlight",this.checked)
})

// That is the function called when there is a mutation event
var callback = function(mutationsList) {
 for(var mutation of mutationsList) {
   if (mutation.type == 'attributes') {
    console.log("The attribute '" + mutation.attributeName + "' was modified.");
   }
 }
};

// The mutation observer
var observer = new MutationObserver(callback);
observer.observe(square, { attributes: true });
<div id="mydiv" aria-highlight="false" style="background: red; height: 100px; width: 100px"></div>
<label for="highlight"><input type="checkbox" id="highlight">Highlight Div</label>

【讨论】:

  • 感谢您的帮助,非常感谢
  • 另一个问题!你如何访问观察者中的元素
  • mutation.target。试试console.log(mutation.target.style.background) 玩吧 ;)
  • 非常感谢
猜你喜欢
  • 2018-01-26
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
相关资源
最近更新 更多