2017-06-05 5 views
2

contenteditable divのテキストオーバーフローを検出しようとしていますので、divの幅(800px)の後にテキストを入力すると、オーバーフローについて警告します。私は以下のコードを試しています。contenteditableでテキストのオーバーフローを検出する方法

HTML

var e = document.getElementById('test'); 
 
if (e.offsetWidth < e.scrollWidth) { 
 
    alert("Overflow"); 
 
}
#test{ 
 
    max-width: 800px; 
 
    text-overflow: ellipsis; 
 
    white-space: nowrap; 
 
    overflow:hidden; 
 
    font-size: 76px; 
 
}
<div class="content" contenteditable="true"> 
 
    <div id="test">Click here..</div> 
 
</div> 
 

 

 

+2

あなたのコードは正しく動作していますが、 'max-width:800px'の後ろに'; 'がありません。 widthプロパティがapply.Add ';'&は動作しません。 – brk

+1

私は ';'を追加しましたが、javascriptを使って 'ellipsis'を検出したい –

答えて

1

下記お試しください:関数がかかりました

$(document).ready(function(){ 
 
    $('.content').on('input',function(){ 
 
    var e = document.getElementById('test'); 
 
    $.fn.textWidth = function() { 
 
     var htmlCalc = $('<span>' + this.html() + '</span>'); 
 
     htmlCalc.css('font-size', this.css('font-size')) 
 
     .hide() 
 
     .prependTo('body'); 
 
     var width = htmlCalc.width(); 
 
     htmlCalc.remove(); 
 
     return width; 
 
    }; 
 
    if ($('#test').textWidth() > $('#test').width()) { 
 
     alert("Overflow"); 
 
    } 
 
    }); 
 
});
#test{ 
 
    max-width: 800px; 
 
    text-overflow: ellipsis; 
 
    white-space: nowrap; 
 
    overflow:hidden; 
 
    font-size: 76px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="content" contenteditable="true"> 
 
    <div id="test">Click here..</div> 
 
</div>

.textwidth()をnからhere

関連する問題