简体   繁体   中英

Weird JavaScript bug in Chromium based browsers

For a school exercise, I'm trying to increase the width of a button using Javascript.

This is my code:

 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. This only happens in Chromium based browsers (Chrome, Edge, Brave). What makes this even weirder is that the code runs fine on my other laptop running the exact same versions of Chrome and Edge. In Firefox and IE9, it also works fine. I've tried cleaning my cache, and even installed a new browser (Vivaldi), which has the same problem. I am running Windows 10 version 1909 build 18363.1256. For Chrome I'm on version 87.0.4280.88, Brave, version 87.0.664.66, and Edge, version 87.0.664.66.

Using the function getBoundingClientRect() fixes the issue.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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