如何用JavaScript修改HTML中动态生成div的style宽度为auto?
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

