所选文本的宽度 - jquery

时间:2015-09-10 04:17:04

标签: jquery

我试图以像素为单位获取所选文字的宽度并将其显示为alert();。这是否存在?

编辑(从我下面写的评论中复制)

我做了很多努力,但一切都是徒劳的,现在我试图看看我是否可以获得selection.toString()的价值然后将其绑定到.width()如果我能做到的话它,我非常确定我可以将它们结合起来以获得我正在寻找的宽度。

编辑12:42上午

我试过这个

if(selection.toString() != '' ){
    var selected = selection.toString();
    alert($(selected).width());
}

我得到null

的值

3 个答案:

答案 0 :(得分:0)

试试这个:

DEMO

JS:

function getSelectionDimensions() {
    var sel = document.selection, range;
    var width = 0, height = 0;
    if (sel) {
        if (sel.type != "Control") {
            range = sel.createRange();
            width = range.boundingWidth;
            height = range.boundingHeight;
        }
    } else if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0).cloneRange();
            if (range.getBoundingClientRect) {
                var rect = range.getBoundingClientRect();
                width = rect.right - rect.left;
                height = rect.bottom - rect.top;
            }
        }
    }
    return { width: width , height: height };
}

REFRENCE LINK

答案 1 :(得分:0)

如果元素没有固定宽度但是动态包含,这可能对你有用吗?

<p id="random">testing</p>

var elem   = document.getElementById('random');
var height = elem.offsetHeight;
var width  = elem.offsetWidth;

alert(height + ' x ' + width);

offsetHeight可以工作,但offsetWidth会给你它所在容器的宽度,所以如果它在自己的元素中动态调整大小,你应该能够获得准确的宽度。

答案 2 :(得分:0)

似乎我发现了我在找什么,代码似乎有点基本,因为我是jquery的新手

 $(function(){
        $(document.body).bind('mouseup', function(e){
            var selection;


            if (window.getSelection) {
              selection = window.getSelection();
            } 

            if(selection.toString() != '' ){
                 $(".position").show();
                var select = selection.toString() ; 
               //some code
                $(".hiden").html(select);
                var width = $(".hiden").width();
                var height = $(".hiden").height();
            }

我使用了我进入var select的值并将其添加到我的html代码的隐藏范围内,然后我计算了它的宽度,并尝试了高度和工作。

谢谢你的帮助。

相关问题