首页 > 解决方案 > 在控制台中显示黄色警告消息

问题描述

我想在 Chrome 控制台中显示一条警告消息,例如此屏幕截图中突出显示的项目:

该消息具有浅黄色背景和棕色文本,并以黄色警告三角形开头。

console.log(message)显示一条正常的白色消息。

console.error(message)创建错误消息。

但是使用console.warning(message)回报Uncaught TypeError: console.warning is not a function.

那么有没有办法为 JavaScript 提供控制台警告呢?

它应该是这样的:

(function() {
  var newbgcolor = document.getElementById('mycolor').value;
  document.getElementById('output').style.backgroundColor = newbgcolor;
});

function update() {
  var mycolorvalue = document.getElementById('mycolor').value;
  if (mycolorvalue != "#000000") {
    document.getElementById('output').style.backgroundColor = mycolorvalue;
  } else {
    console.warning("Text will be hard to read!"); // <-- error happens
  }
}
#output {
  background-color: #00ffff;
}
<!DOCTYPE html public "-//W3C//HTML 4.01 Transitional//EN">
<html>

<head>
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
</head>

<body>
  <p>Background color:</p>
  <input type="color" id="mycolor" value="#00ffff" oninput="update()" />
  <p id="output">You will see the change here.</p>
</body>

</html>

但它不起作用。我该怎么做呢?

编辑:我可以使用自定义 CSS!

console.log(
  "%c Foo",
  "display:block;width:100%;background-color: #332B00;color:#F2AB26;"
);

但它看起来并不正确:
失败的尝试

标签: javascriptwarningsconsole.log

解决方案


尝试使用console.warn方法而不是console.warning.

例子

console.warn("A sample warning message!");

参考

这是一个包含可用控制台方法的完整列表的资源: https ://developer.mozilla.org/en-US/docs/Web/API/console#methods


推荐阅读