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

如何用JavaScript修改HTML中动态生成div的style宽度为auto?

Solution to Fix Dynamic Div Width Issue

Got it, let's get your title text displaying properly by adjusting the div's width style! Here's how to modify your template code:

1. For All Dynamic Divs (Set Width to Auto Globally)

If every generated div needs to have an auto-width to fit the title content, simply replace the fixed Width:150 style in your template with width:auto:

template: function (o) {
  return "<div style='width:auto'> <span>" + o.Title + "</span></div>";
}

I also switched to lowercase width for CSS property consistency—this is a best practice and avoids any potential case-sensitivity issues in some browsers.

2. For Specific Divs (Conditional Width Adjustment)

If only some of the dynamic divs need the auto-width (others can keep the 150px width), add a conditional check based on a property in your o object. For example, if you have a flag like o.isLongTitle to identify titles that need more space:

template: function (o) {
  // Determine the width style based on your condition
  const widthStyle = o.isLongTitle ? "width:auto" : "Width:150";
  // Use template literals for cleaner syntax (optional but recommended)
  return `<div style='${widthStyle}'> <span>${o.Title}</span></div>`;
}

This way, only the divs that match your condition will get the auto-width, while others retain the original fixed width.

内容的提问来源于stack exchange,提问作者S syed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:10:21