IE11/Edge设置元素尺寸报错:严格模式下不可赋值只读属性
getBoundingClientRect() Hey there, I see exactly what's going on here—IE11 and old Edge are being sticklers about strict mode and read-only properties, which modern browsers let slide a bit. Let's break this down and fix it:
The Root Cause
When you call getBoundingClientRect(), it returns a DOMRect (or ClientRect in IE11) object whose properties (width, height, top, etc.) are read-only by design. Modern browsers might ignore attempts to overwrite these properties in non-strict mode, but IE11/old Edge enforces strict mode rules strictly—so trying to assign visContainerBounds.width -= ... throws that error you're seeing.
The Solution: Create a Mutable Copy
Instead of modifying the original read-only object directly, make a copy of its properties into a new, mutable object, then adjust the values there. Here are a couple of ways to do this:
Option 1: Modern Syntax (Works in Most Browsers, Except IE11)
Use the spread operator to copy all properties into a new object, then override the width/height:
const visContainerBounds = this.visContainer.getBoundingClientRect(); const adjustedBounds = { ...visContainerBounds, width: visContainerBounds.width - this.marginHorizontal, height: visContainerBounds.height - this.marginVertical // Fill in your missing margin variable here }; // Use adjustedBounds for your sizing logic now
Option 2: IE11-Compatible Syntax
If you need full support for IE11, use Object.assign() to clone the properties, then modify the new object:
const visContainerBounds = this.visContainer.getBoundingClientRect(); // Clone the read-only object into a mutable one const adjustedBounds = Object.assign({}, visContainerBounds); // Now safely adjust the dimensions adjustedBounds.width -= this.marginHorizontal; adjustedBounds.height -= this.marginVertical;
Option 3: Manual Property Copy (Most Explicit)
If you only need specific properties, you can manually copy them to avoid any compatibility edge cases:
const visContainerBounds = this.visContainer.getBoundingClientRect(); const adjustedBounds = { width: visContainerBounds.width - this.marginHorizontal, height: visContainerBounds.height - this.marginVertical, // Include any other properties you need (top, left, etc.) top: visContainerBounds.top, left: visContainerBounds.left };
Why This Works
By creating your own mutable object, you're bypassing the read-only restriction of the native DOMRect/ClientRect. IE11/old Edge won't throw errors because you're modifying properties on a regular JavaScript object, not the locked-down browser-provided one.
内容的提问来源于stack exchange,提问作者Joe Warner

