限制格式化用户输入的宽度 - Javascript、CSS 或 jQuery

发布于 2024-09-17 17:28:46 字数 318 浏览 11 评论 0原文

如何防止格式化的用户输入超过最大宽度? (例如,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埋情葬爱 2024-09-24 17:28:46

我已经可以找到的宽度
格式化字符串。问题在于
它的实际缩短。

我认为考虑到您的问题,可以从格式化条目中删除最后一个字符。您只需递归地挖掘 HTML 结构,直到找到它。看看我写的这个简洁的小函数:

function findLastElement(element){
    var content = $.trim(element.html());

    if(content.charAt(content.length - 1) === '>'){
        var lastChild = element.children(':last');
        if(lastChild.length > 0){
          return findLastElement(lastChild);
        }
    }

    return element;
}

这个名字有点误导,但是这个函数会挖掘你传递给它的 jQuery 元素来找到包含最后一个字符的元素,所以我认为这会解决你的问题。

附言。如果这里的任何一位专家愿意在评论中提出一个建议,我很乐意接受有关如何优化/采用这段代码的最佳实践的任何建议。

I can already find the width of the
formatted string. The problem is in
the actually shortening of it.

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:

function findLastElement(element){
    var content = $.trim(element.html());

    if(content.charAt(content.length - 1) === '>'){
        var lastChild = element.children(':last');
        if(lastChild.length > 0){
          return findLastElement(lastChild);
        }
    }

    return element;
}

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.

黑色毁心梦 2024-09-24 17:28:46

我们可以假设只使用某种字体吗?这可能会有所帮助:

使用 JavaScript 计算文本宽度

Can we assume only a certain font will be used? This one might help:

Calculate text width with JavaScript

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文