javascript - 基于 Chromium 的浏览器中奇怪的 JavaScript 错误

标签 javascript html google-chrome microsoft-edge chromium

在学校练习中,我尝试使用 Javascript 增加按钮的宽度。

这是我的代码:

const button = document.querySelector("button");

button.addEventListener("click", () => {
  console.log(button.offsetWidth);
  button.style.width = button.offsetWidth + 1 + "px";
});
<button>Press me!</button>

For some reason, the width stops increasing after 3 clicks.这只发生在基于 Chromium 的浏览器(Chrome、Edge、Brave)中。更奇怪的是,代码在我的另一台运行完全相同版本的 Chrome 和 Edge 的笔记本电脑上运行良好。在 Firefox 和 IE9 中,它也可以正常工作。我试过清理我的缓存,甚至安装了一个新的浏览器 (Vivaldi),它也有同样的问题。我正在运行 Windows 10 版本 1909 内部版本 18363.1256。对于 Chrome,我使用的是版本 87.0.4280.88、Brave 版本 87.0.664.66 和 Edge 版本 87.0.664.66。

最佳答案

使用函数 getBoundingClientRect() 解决了这个问题。

const button = document.querySelector("button");

button.addEventListener("click", () => {
  console.log(button.getBoundingClientRect().width);
  button.style.width = button.getBoundingClientRect().width + 1 + "px";
});
<button>Press me!</button>

关于javascript - 基于 Chromium 的浏览器中奇怪的 JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65589614/

相关文章:

javascript - wkhtmltopdf.exe --no-stop-slow-scripts 不起作用?

javascript - 使用 accept 捕获的 Polyfill 文件输入(使用 getUserMedia 捕获?)

javascript - 使用 JavaScript 设置选择框值

javascript - 表单验证转到下一页

google-chrome - Google Chrome 不尊重 manifest.json 中的键值?

javascript - 外部 Javascript 文件在 HTML 文件中不起作用

jquery - 如何使用 jQuery 从文件中添加内容?

css - 如何垂直对齐 `inline-block` 元素内的 `<td>` 元素?

google-chrome - 谷歌浏览器无法正确呈现谷歌网络字体

ruby-on-rails - X-Frame-Options ALLOW-FROM 特定站点允许所有