JQuery找到div可以包含的字符串的长度 [英] JQuery find the length of string that div can contain

查看:120
本文介绍了JQuery找到div可以包含的字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Div,它没有固定高度或宽度。
div将包含一些文本,字符串的长度不能修复。如果字符串太长而无法放入div,则文本将出现在div外部,我需要的是根据div的宽度和高度知道div可以包含的最大字符串长度。

$ b $除非你使用固定宽度的字体,其中所有的字符都是相同的宽度(这是不寻常的),你的问题是没有答案的。在给定的宽度内有多少个字符取决于字符是什么样的,因为像W这样的字符比所有可变宽度字体中的i字符宽得多。



如果您使用的是固定宽度的字体,则需要测量您使用的字体和字体大小以及字体样式的字符宽度。然后,您可以简单地将您所拥有的宽度除以字符宽度,并确定将有多少个字符适合。



可以通过创建一个div来测量固定宽度的字体无边距,填充或边框,将样式设置为 position:absolute ,在其上设置所需的font-family和font-size并在div中放置一个字符。然后你可以通过获取它的offsetWidth来获取div的宽度。



请参阅 http://jsfiddle.net/jfriend00/kHHU7/ 为一个简单的例子。



这是一个函数,用于度量字符的宽度以固定宽度的字体显示:

  function getCharWidth(fontFamily,fontSize){
var div = document.createElement( DIV);
div.style.position =绝对;
div.style.visibility =hidden;
div.style.fontFamily = fontFamily;
div.style.fontSize = fontSize;
div.innerHTML =S;
document.body.appendChild(div);
var width = div.offsetWidth;
document.body.removeChild(div);
return(width);
}

你可以在这里看到它的工作:

I have a Div, which dosn't have fix height or width. the div will contain some text, the length of string not fix. if the String is too long to fit in the div, the text will appear outside the div, what I need is to know how much maximum length of String the div can contain based on it's width and height.

Unless you are using a fixed width font where all characters are the same width (which is unusual), there is no answer to your question. How many characters fit in a given width depends upon what the characters are as characters like a "W" are much wider than characters like an "i" in all variable width fonts.

If you are using a fixed width font, then you need to measure how wide a character is in the font and font-size and font-style you're using. You can then simply divide the width you have by the character width and determine how many characters will fit.

It is possible to measure a fixed width font, by creating a div with no margin, padding or border, setting the style to position: absolute, setting the desired font-family and font-size on it and putting one character in the div. You can then fetch the width of the div by getting it's offsetWidth.

See http://jsfiddle.net/jfriend00/kHHU7/ for a simple example.

Here's a function that measure's the width of a character in a fixed width font:

function getCharWidth(fontFamily, fontSize) {
    var div = document.createElement("div");
    div.style.position = "absolute";
    div.style.visibility = "hidden";
    div.style.fontFamily = fontFamily;
    div.style.fontSize = fontSize;
    div.innerHTML = "S";
    document.body.appendChild(div);
    var width = div.offsetWidth;
    document.body.removeChild(div);
    return(width);
}

You can see it work here: http://jsfiddle.net/jfriend00/y4eZr/

这篇关于JQuery找到div可以包含的字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆