繁体   English   中英

在加载时运行两个 javascript 函数,一个取消另一个

[英]running two javascript functions on load, one cancels the other out

我是 javascript 的初学者,我试图确保 updateStyle 和 changeColor 都可以工作,但是当我在最后添加 changeColor() 时,它可以工作,但是 updateStyle() 不起作用,我怎样才能让它们都发生在加载? updateStyle 将所有 H1 标签更改为 Comic sans,并且 changeColor 使 H1 中的每个字母都具有不同的随机颜色,在理想的世界中:这两种情况都会发生,如下代码所示。 H1 中的每个字母都是不同的颜色,但字体保持自动。 如果我删除 changeColor() (最后),那么 H1 总是在漫画中。 如果相关的话,这适用于谷歌扩展。

'use strict'

let fontOverwrite = 'h1 {font-family: Comic Sans MS !important}'
let transformOverwrite = 'h1 {text-transform:uppercase}'

// if we don't have the styleDom, create it
let styleDom = document.getElementById('comic-sans-everything-style')
if (!styleDom) {
  styleDom = document.querySelector('h1').appendChild(document.createElement('style'))
  styleDom.id = 'comic-sans-everything-style'
  styleDom.rel = 'stylesheet'
  styleDom.type = 'text/css'
}
const updateStyle = () => {
  window.chrome.storage.sync.get(['status', 'uppercase'], (items) => {
    if (!window.chrome.runtime.error) {
      if (items.status && items.uppercase) {
        styleDom.innerText = fontOverwrite + transformOverwrite
      } else if (items.status) {
        styleDom.innerText = fontOverwrite
      } else {
        styleDom.innerText = ''
      }
    }
  })
}



// ADDED to make letters rainbow :)

function changeColor() {
var paragraphs = document.getElementsByTagName("h1");

for(var i = 0; i < paragraphs.length; i++)
{
    var innerText = paragraphs[i].innerHTML;
    var innerTextSplit = innerText.split("");
    paragraphs[i].innerText = "";

    var isHTMLElement = false;

    for(var j = 0; j < innerTextSplit.length; j++) {
        if(innerTextSplit[j] == "<")
          isHTMLElement = true;

        if(!isHTMLElement){
          var randomColor = "rgb(" + Math.floor((Math.random() * 255) + 1) + ", " + Math.floor((Math.random() * 255) + 1) + ", " + Math.floor((Math.random() * 255) + 1) + ");"
          innerTextSplit[j] = '<span style="color: ' + randomColor + '">' + innerTextSplit[j] + '</span>';
        }

        if(innerTextSplit[j] == ">")
            isHTMLElement = false;

    }

    innerTextSplit = innerTextSplit.join('');
    paragraphs[i].innerHTML += innerTextSplit;
}
}


//THIS is where i'm trying to make the functions happen, when they're both there ONLY changeColor() works


// run once on file load
updateStyle()
changeColor()

首先尝试以这种方式声明您的 function:

function updateStyle(){

window.chrome.storage.sync.get
(['status', 'uppercase'], 
(items) => {
if 
(!window.chrome.runtime.error) 
{
  if (items.status && 
  items.uppercase) {
  styleDom.innerText = 
  fontOverwrite + 
  transformOverwrite
  } else if (items.status) {
    styleDom.innerText = 
    fontOverwrite
  } else {
    styleDom.innerText = ''
  }
}
})
} 

其次加“;” 到您的 function 通话结束

更新风格(); 换颜色;

希望有帮助

暂无
暂无

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

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