限制格式化用户输入的宽度 - Javascript、CSS 或 jQuery
如何防止格式化的用户输入超过最大宽度? (例如,800 像素) 用户输入被格式化,因为它被输入到所见即所得文本编辑器(CK 编辑器)中。
此解决方案不起作用:
// Replicate user input in hidden div
// Check width
// If width > 800px, remove characters
...因为您将从格式化条目中删除字符 - 例如,从 Hello World 你好世界
您最终会得到
How do you prevent formatted user input past a max width? (e.g., 800 pixels) The user input is formatted because it is entered into a WYSIWYG text editor (CK Editor).
This solution doesn't work:
// Replicate user input in hidden div
// Check width
// If width > 800px, remove characters
...because you'd be removing characters from a formatted entry - e.g., from <p>Hello World</p>
you'd end up with <p>Hello World</p
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为考虑到您的问题,可以从格式化条目中删除最后一个字符。您只需递归地挖掘 HTML 结构,直到找到它。看看我写的这个简洁的小函数:
这个名字有点误导,但是这个函数会挖掘你传递给它的 jQuery 元素来找到包含最后一个字符的元素,所以我认为这会解决你的问题。
附言。如果这里的任何一位专家愿意在评论中提出一个建议,我很乐意接受有关如何优化/采用这段代码的最佳实践的任何建议。
I think given your problem it is possible to remove the last char from a formatted entry. You'd just have to recursively dig through your HTML structure till you find it. Have a look at this neat little function I've written:
The name is slightly misleading, but this function will dig through the jQuery element you pass to it to find the element containing the last character, so I think this will solve your problem.
PS. I'd readily accept any suggestion on how to optimize/adopt best practice with this piece of code, if any of the gurus here would kindly drop one in the comments.
我们可以假设只使用某种字体吗?这可能会有所帮助:
使用 JavaScript 计算文本宽度
Can we assume only a certain font will be used? This one might help:
Calculate text width with JavaScript