You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

元素宽高修改失败、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 native width HTML attribute. For most block/inline elements, width is controlled via the CSS style property, not an HTML attribute. That's why getAttribute("width") returns null—the attribute doesn't exist on your element.
  • scrollWidth is a read-only property that reflects the actual width of the element's content (including overflow). You can't animate or set it directly with animate().

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 like px) to modify inline width styles.
  • For more reliable width checks, use getComputedStyle(commentContainer).width instead of style.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 like scrollWidth.

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 than box.style.width which 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 initialScrollHeight instead of 51px makes the code responsive to different textarea sizes and browser default styles.
  • Remove arbitrary 25px addition: The scrollHeight already 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:52:26