开发者

Limit width of formatted user input - Javascript, CSS or jQuery

开发者 https://www.devze.com 2023-01-14 12:04 出处:网络
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).

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开发者_JAVA技巧 - e.g., from <p>Hello World</p> you'd end up with <p>Hello World</p


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.


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

Calculate text width with JavaScript

0

精彩评论

暂无评论...
验证码 换一张
取 消