简体   繁体   中英

Limit contenteditable div to visible part

I have a div, which has contenteditable=true . Now, if I enter a longer text, it goes over the bottom. I don't want that. I want the text to stop and block any other text.

This is the solution like I want to have it: http://jsfiddle.net/37Jnn/

The problem here is that this is a textarea and it isn't working with my editable div .

Here is my editable div: http://jsfiddle.net/N4tTp/1/

Any thoughts?

Credit goes to Mohsen but I think this post should have a formal answer: You're looking for the css style of:

overflow:hidden;

on the div in question. To make the div scrollable, set overflow to:

overflow:auto;

You could save the state of the div (original and after each successful input) and after input events check the div size and restore the state if the size is too big.

The advantage of this solution over the overflow:hidden; one is that the div actually doesn't have the extra content. If someone was to select all the text in it after inputting too much, the extra characters wouldn't be part of the selection.

While it isn't the most elegant way to do it, it does work.

HTML:

<div class="myDiv" contenteditable=true>This text is in the box.... but this is not in the box</div>

CSS:

.myDiv {
    background: #acacac;
    width:60px;
    height: 60px;
    overflow: hidden;
}

Javascript:

var text = undefined;
$(function(){
    while($('.myDiv').get(0).scrollHeight > $('.myDiv').height()) {
        $('.myDiv').text($('.myDiv').text().slice(0,-1));
    }
});
$('.myDiv').bind('keydown', function(e) {
    text = $('.myDiv').text();
    if($('.myDiv').get(0).scrollHeight > $('.myDiv').height() && e.which != 8) {
        e.preventDefault();
    }
});
$('.myDiv').bind('keyup', function() {
    if($('.myDiv').get(0).scrollHeight > $('.myDiv').height()) {
        $('.myDiv').text(text);
    }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM