Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过更改容器的宽度来对齐文本_Javascript_Dom_Text_Width - Fatal编程技术网

Javascript 通过更改容器的宽度来对齐文本

Javascript 通过更改容器的宽度来对齐文本,javascript,dom,text,width,Javascript,Dom,Text,Width,我希望工具提示中的文本是对的,但不像css中那样,通过在单词之间留出大的空格,而是通过调整容器宽度 例如,下面是工具提示 如果有很多文本,我不希望工具提示延伸到1000px,所以我将最大宽度设置为300px 通过设置“最大宽度”,如果我稍微加宽容器,工具提示看起来非常完美,在本例中为15px 或者可能有一种情况,我想缩小元素范围,使文本完全适合 最好的方法是什么 我能想到的最好的方法是得到最后一个单词,把它包成一个跨距,测量到边缘的距离,如果小于50%,则加宽或如果大于50%,则收缩容器,直到

我希望工具提示中的文本是对的,但不像css中那样,通过在单词之间留出大的空格,而是通过调整容器宽度

例如,下面是工具提示

如果有很多文本,我不希望工具提示延伸到1000px,所以我将最大宽度设置为300px

通过设置“最大宽度”,如果我稍微加宽容器,工具提示看起来非常完美,在本例中为15px

或者可能有一种情况,我想缩小元素范围,使文本完全适合

最好的方法是什么


我能想到的最好的方法是得到最后一个单词,把它包成一个跨距,测量到边缘的距离,如果小于50%,则加宽或如果大于50%,则收缩容器,直到容器的高度发生变化,这意味着添加或删除了行

获取所需字符串的长度并应用所需的格式

这是我思考的一个很快的例子。我希望我能详细说明,但你知道,有很多事情要做。希望能有帮助

HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="tooltip">
            <p class="msg">Pork belly</p>
        </div>
        <div class="tooltip">
            <p class="msg">Pork belly synth narwhal meggings next level before they sold out Carles mlkshk chia Brooklyn</p>
        </div>
        <div class="tooltip">
            <p class="msg">Wes Anderson literally flannel Godard letterpress. Pinterest Carles artisan, PBR whatever cray cliche sustainable banjo fanny pack occupy Bushwick. +1 cred disrupt, DIY you probably haven't heard of them slow-carb blog authentic Portland </p>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script src="behavior.js"></script>
</body>
</html>
JS

$(function() {
$.each($('.tooltip'), function(index, val) {
    var msgLength = $('.msg',this).html().length;
    if (msgLength <= 20) {
        $(this).addClass('tiny');
    }
    else if(msgLength <= 100){
        $(this).addClass('medium');
    }
    else{
        $(this).addClass('big');
    }
});
});
$(函数(){
$.each($('.tooltip'),函数(索引,val){
var msgLength=$('.msg',this.html().length;
如果(msgLength试试这个:

它通过注入隐藏元素来获取字符串的实际宽度,然后将工具提示的宽度设置为实际字符串的宽度(如果它在
delta

$(document).ready(function() {
    $('.tooltip').each(function() {
        var $this = $(this);
        var delta = 20;

        // get the real width of the string
        var $tester = $('<div class="tester" />').appendTo('body').text($this.text());
        var stringWidth = $tester.width();
        $tester.remove();

        if($this.width()+delta > stringWidth) {
            $this.width(stringWidth);
        }
    });
});
$(文档).ready(函数(){
$('.tooltip')。每个(函数(){
var$this=$(this);
varδ=20;
//获取字符串的实际宽度
var$tester=$('').appendTo('body').text($this.text());
var stringWidth=$tester.width();
$tester.remove();
如果($this.width()+delta>stringWidth){
$this.width(stringWidth);
}
});
});
希望我能帮上一点忙,我想我需要一点帮助,但这应该能让你明白这个想法


我仔细考虑了这一点,得出了一个结论,一个纯CSS解决方案可能就是您正在搜索的。您可以将工具提示设置为
display:inline block
,这样它将只占据文本所需的位置(这解决了您缩小的用例),然后将
max width
设置为您所需的宽度


再次检查。

这里是新的,但是已经编码20年了。我的答案属于“也许不要那样做,试试这个”

有没有什么特别的原因让你需要仔细地定制宽度?要为一段特定的文本获得所需的空间并不容易,特别是如果你必须支持多个浏览器和操作系统的话

我最近不得不在Microsoft Dynamics CRM内的自定义网页中添加工具提示。该网页是ASP,默认工具提示非常糟糕。我在jquery上玩了一段时间,但一无所获

我从MenuCool找到了tooltip.js,并快速轻松地实现了它。免费试用,展示给我的老板。她喜欢。一个域及其所有子域的许可证要20美元

在将css和js文件放入适当的文件夹并将其添加到页面后,如下所示:

<script src="Scripts/tooltip.js" type="text/javascript"></script>
<link href="Styles/tooltip.css" rel="stylesheet" type="text/css" />
onmouseover="tooltip.pop(this, this.value)"
很简单,一个漂亮的弹出窗口。它看起来很可定制,但我自己并不为此烦恼。

小提琴:

/*css*/
身体{
字体系列:Arial,“Helvetica Neue”,Helvetica,无衬线;
字体大小:12.6px;
}//使字体正确
.刀尖{
显示:内联块;
单词break:打破一切;
}//工具提示设置为内联块,以便它包装文本我们可以计算文本宽度
/*将“宽度”设置为工具提示后,将添加“提示范围”类*/
.提示:之后{
内容:“”
}
.提示跨度:最后一个孩子:之后{
内容:“”
}
乌尔里希斯多洛里弗林尼亚奥纳雷。
前庭,
/*JS*/
//获取工具提示中的文本
var arr=$('.tip')[0].innerHTML.split(/\s+/);
//用span包装每个单词并附加到工具提示
对于(i=0;iif(setWidth)您正在使用jQuery(max width表示您正在使用)?此外,如果不添加空格,则不太可能完全对齐文本,除非行中的单词的总长度都以相同的长度结束。您的公式听起来与max width已经做的类似,即尝试获取尽可能多的单词以匹配长度,如果不匹配,则进行换行。或者您希望使用一种算法来试验不同的长度找到最佳宽度的长度?@Tomas-您的意思是这样的吗?(使用
inline block
将基于文本的宽度设置为
max width
,然后,很可能是
text align:center
(如果是换行的话)?当你描述这个答案时,计算max根本不试图解决这个问题,甚至没有给出一个令人信服的理由“不要那样做”:有几种方法(如其他答案所示)在一个可接受的系统范围内确定宽度。OP大概也有一个工具提示系统:花费超过一半的帖子在一个付费工具提示插件上,你承认没有完全探索过,这是离题的。一个关于可变宽度工具提示如何伤害用户界面的建议,或者一个关于这个插件或其他插件如何帮助用户的解释解决这个问题
onmouseover="tooltip.pop(this, this.value)"
 /* css */
   body {
            font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
            font-size: 12.6px;
        } // to make font proper


  .tool-tip {
            display: inline-block;
            word-break: break-all;
        } // tool-tip set to inline-block, so that it wraps text we can calculate text width

  /* tip-span class is added after setting width to tooltip */
  .tip-span:after {
                content: " "
            }
  .tip-span:last-child:after {
                content: ""
            }

<div class="tool-tip" id="tip" >
    Maecenas ultricies dolor id fringilla ornare. 
    Vestibulum quis semper quam, 
</div>
<div class="invisible" id="invisible"></div>

    /* JS */
    //get text inside tool-tip 
    var arr = $('.tip')[0].innerHTML.split(/\s+/); 

    //wrap each word with span and append to tool-tip
    for( i=0; i< arr.length; i++  ) {
        html += "<span>";
        html += arr[i];
        html += "</span>";
    }
    $('.tip')[0].innerHTML = html;


    // len = no: of words
    // get total width of text by calculating total tool-tip width 
    var tip_width = $('.tip').width();

   // find by which number, tip_width is divisible. it is the no of lines or no of rows of text
   // calculate width
   // width = ( tip_width + ( no:of words * ( width taken by a space ) ) ) / no: of rows
    for( i=2; i< len; i++ ) {

        if( ( tip_width % i ) == 0 ){
            setWidth = ( tip_width + (len * spaceWidth) ) / i;      
            if( setWidth <= 300 ) { // rows will choosen if it is lesser than 300
                console.log( i )
                break;
            }
        }

    }

  //set width to tool tip
  tip.css({ 'width': setWidth+'px' });