2 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
為什么不嘗試將指標(biāo)保存到localstorageorsessionstorage中,并在 if 條件中添加此驗(yàn)證:
您的代碼片段:
...
// Use local or session storage
let hasReloaded = localStorage.getItem('hasReloaded')
if (header && chromeAgent && !hasReloaded) {
console.log('funciton triggered')
let htmlTag = document.getElementsByTagName('html');
let isInverted = htmlTag[0].getAttribute('hc') != null
header.classList.toggle('inverted', isInverted)
// Set hasRealoaded to true
localStorage.setItem('hasReloaded', true)
window.location.reload()
}
...

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊
您不需要為此重新加載頁面,您需要MutationObserver
.
這將在特定元素上查找文檔中的更改。
當(dāng)hc
屬性被動(dòng)態(tài)添加到頁面時(shí),它將在添加或刪除它時(shí)進(jìn)行偵聽。
"High Contrast", "a4"
如果打開高對(duì)比度模式(“a4”根據(jù)設(shè)置更改)和“高對(duì)比度關(guān)閉”如果插件未激活,則以下將記錄。
下面的美妙之處在于,根據(jù)設(shè)置“a3”、“a4”等,您可以應(yīng)用不同的樣式。
當(dāng)插件被禁用時(shí),下面的內(nèi)容有些不正確,好像兩次觸發(fā)“高對(duì)比度關(guān)閉”,因此您需要對(duì)此進(jìn)行調(diào)查。(這是因?yàn)楫?dāng)插件關(guān)閉時(shí),它首先將狀態(tài)設(shè)置為“a0”,然后刪除屬性,在正常使用下應(yīng)該沒問題,但只是需要注意的一點(diǎn))。
const targetNode = document.documentElement;
// Options for the observer (which mutations to observe)
const config = { attributes: true};
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
let name = "";
for(let mutation of mutationsList) {
if (mutation.type === 'attributes') {
if(mutation.attributeName == "hc"){
if(mutation.target.attributes.getNamedItem(mutation.attributeName) != null && mutation.target.attributes.getNamedItem(mutation.attributeName).value != "a0"){
console.log("High Contrast", mutation.target.attributes.getNamedItem(mutation.attributeName).value);
}else{
console.log("High Contrast Off");
}
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
添加回答
舉報(bào)