元素宽高修改失败、jQuery转TypeScript及textarea布局异常求助
Solutions to Your Frontend Technical Issues
Hey there, let's break down each of your problems and fix them step by step:
1. Fixing Unresponsive Element Width Modification & Null Attribute Issue
The core issues here are twofold:
- You're using
setAttribute("width")to modify an element's width, which only works for elements like<img>or<table>that have a nativewidthHTML attribute. For most block/inline elements, width is controlled via the CSS style property, not an HTML attribute. That's whygetAttribute("width")returnsnull—the attribute doesn't exist on your element. scrollWidthis a read-only property that reflects the actual width of the element's content (including overflow). You can't animate or set it directly withanimate().
Corrected Code:
// Ensure the element is typed as HTMLElement const commentContainer = this.commentContainer as HTMLElement; // Use style.width instead of HTML attributes for width control if (commentContainer.style.width !== "0px") { console.log("Current scrollWidth: " + commentContainer.scrollWidth); // Animate the CSS width property, not the read-only scrollWidth commentContainer.animate({ width: "0px" }, { duration: 300 }); // Persist the final width after animation commentContainer.style.width = "0px"; } else { console.log("Width is currently 0, scrollWidth: " + commentContainer.scrollWidth); commentContainer.animate({ width: "285px" }, { duration: 300 }); commentContainer.style.width = "285px"; }
Key Notes:
- Always use
element.style.width(with units likepx) to modify inline width styles. - For more reliable width checks, use
getComputedStyle(commentContainer).widthinstead ofstyle.width—this accounts for styles from CSS classes, not just inline styles. - The Web Animations API (
animate()) targets CSS properties, not read-only DOM properties likescrollWidth.
2. Converting jQuery Slide Animation to TypeScript
The jQuery code relies on animating the width CSS property. Here's how to replicate that behavior in vanilla TypeScript, using the Web Animations API for smooth transitions:
Full TypeScript Implementation:
// Wait for the DOM to fully load before accessing elements document.addEventListener("DOMContentLoaded", () => { // Get elements with type assertions (critical for TypeScript type safety) const slideButton = document.querySelector(".slide-both") as HTMLButtonElement; const box = document.querySelector(".box") as HTMLElement; // Store the initial rendered width of the box (includes CSS styles) const initialBoxWidth = getComputedStyle(box).width; // Bind click event handler slideButton.addEventListener("click", () => { const currentWidth = getComputedStyle(box).width; if (currentWidth === "0px") { // Animate back to initial width, keep final state with fill: "forwards" box.animate({ width: initialBoxWidth }, { duration: 300, fill: "forwards" }); } else { // Animate to 0 width box.animate({ width: "0px" }, { duration: 300, fill: "forwards" }); } }); });
Key Notes:
- The
fill: "forwards"option ensures the element retains the final animation state (so it stays at 0px or initial width after the animation ends). getComputedStyle()gives you the actual rendered width, including styles from CSS classes—this is more reliable thanbox.style.widthwhich only reads inline styles.- Type assertions (
as HTMLButtonElement) are necessary in TypeScript to access element-specific properties without type errors.
3. Fixing Textarea Height Adjustment Layout Glitches
The issues here come from hardcoding a 51px check and arbitrarily adding 25px to the scrollHeight, which disrupts your layout. Instead, we'll use the textarea's initial scrollHeight as a reference point and adjust dynamically:
Corrected Code:
// Store the initial scrollHeight once, outside the event handler const textArea = document.querySelector("your-textarea-selector") as HTMLTextAreaElement; const initialScrollHeight = textArea.scrollHeight; // Event handler for textarea input/change const adjustTextareaHeight = (e: Event) => { const textArea = e.currentTarget as HTMLTextAreaElement; // Reset height to auto to calculate the correct content height textArea.style.height = "auto"; // Get the actual content height const desiredHeight = textArea.scrollHeight; // Adjust height based on content length relative to initial state if (desiredHeight > initialScrollHeight) { textArea.style.height = `${desiredHeight}px`; } else { // Reset to initial height to fix layout misalignment textArea.style.height = `${initialScrollHeight}px`; } }; // Bind the event listener to the textarea textArea.addEventListener("input", adjustTextareaHeight);
Key Fixes:
- Avoid hardcoded pixel values: Using
initialScrollHeightinstead of51pxmakes the code responsive to different textarea sizes and browser default styles. - Remove arbitrary
25pxaddition: ThescrollHeightalready includes padding and content height—adding extra pixels pushes your layout out of alignment. If you need extra space, add padding to the textarea via CSS instead of manipulating the height. - Reset to initial height on content removal: This ensures the textarea (and adjacent icons) snap back to their original layout when content is deleted.
内容的提问来源于stack exchange,提问作者Peter The Angular Dude
相关产品推荐
相关产品推荐

