在 HTML 文档中全局禁用拼写检查和自动完成?

Disable spellcheck and autocomplete globally in a HTML document?

可以通过向该元素添加标签 spellcheck="false"autocomplete="off" 来禁用单个输入元素的拼写检查或自动完成。

但是对于那些想在整个 DOM 全局禁用它的人来说,有没有办法使用 vanilla javascript 或 HMTL 来做到这一点(考虑到新的输入元素可能在页面的生命周期内创建)?

在 vanilla javascript 中,一种选择是迭代页面上的所有输入并应用必要的属性,如下所示:

var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++){
    inputs[i].setAttribute("spellcheck", "false");
}

对于无法控制新输入的创建的更加动态的情况,可以使用变异观察器将所需属性应用于动态创建:

window.addInput = function(){
  var container = document.getElementById("container");
  var input = document.createElement("input");
  input.setAttribute("type", "text");
  container.appendChild(input);
  container.appendChild(document.createElement("br"));
}

//MutationObserver docs: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
var observer = new MutationObserver(function (e){
  for(var i = 0; i < e.length; i++){
    for(var j = 0; j < e[i].addedNodes.length; j++){
      if(["INPUT", "TEXTAREA"].indexOf(e[i].addedNodes[j].tagName) > -1){
        e[i].addedNodes[j].setAttribute("spellcheck", "false");
        console.log("attribute set")
      }
    }
  }
}).observe(document.getElementById("container"), {childList:true});
<button onclick="addInput();">
Add Input
</button>

<div id="container">

</div>

要处理动态元素,试试这个

document.addEventListener('focus',function(e){
  var elem = e.target;
  if (elem && elem.tagName.toLowerCase()=="input" {
    elem.spellcheck=false;
  }
})

其他循环:

var inp = document.querySelectorAll("input[type=text], textarea");
for (var i=0; i<inp.length; i++){
  inp[i].spellcheck=false;
  inp[i].autocomplete="off";
}

为了能够处理动态创建的元素,您应该使用 DOM Mutation Observers,它可以监视 DOM 节点的更改并在那一点:

// Create the mutation observer
var observer = new MutationObserver(function(mutations) {

  // Loop through the mutations
  mutations.forEach(function(mutation) {
  
    // Loop through the mutation record for that mutation
    for (var i = 0; i < mutation.addedNodes.length; i++){
     
      // Cache current node being added
      var n = mutation.addedNodes[i];
      
      // Check node for an input
      if(n.nodeName === "INPUT"){
        // Set properties as desired
        n.setAttribute("spellcheck", "false");
        n.setAttribute("autocomplete", "off");    
        
        // Confirm changes to new element
        console.log(n);
      }
    }
  });
});

// Start observing the <body>
observer.observe(document.body, { childList: true });

// Dynamically add a new input
document.body.appendChild(document.createElement("input"));