简体   繁体   English

使用 JavaScript 观察者方法更改 aria 属性值

[英]Change aria attribute value using JavaScript Observer method

Can someone provide me with an example of an HTML div element with an attribute of aria-highlight that changes and notifies the element using the JavaScript observer method?有人可以为我提供一个 HTML div 元素的示例,该元素具有 aria-highlight 属性,使用 JavaScript 观察者方法更改并通知元素? An example would be using a checkbox that toggles the div and changes the background of the div element.一个例子是使用一个复选框来切换 div 并更改 div 元素的背景。 I need this done in vanilla JavaScript我需要在香草 JavaScript 中完成此操作

Example HTML示例 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>

So below, you have a checkbox with an event handler to toggle the aria-highlight value.所以在下面,你有一个带有事件处理程序的复选框来切换aria-highlight值。

And an observer which triggers on attribute change from the div.还有一个观察者,它触发 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM