动态输入最大宽度

时间:2017-05-25 09:18:02

标签: javascript jquery css3

我有这个代码,它动态显示文档'div'中输入字段的值。 我已经设置了'div'max-width属性,但它看起来只有在输入字符串中有空格时才有效,如果'div'中没有字符串可以继续...在一条线上。 我该如何解决这个问题?

<!DOCTYPE html>
<html>
<head>
<style>
div {
max-width: 300px;
font-size:40px;
color:red;
font-weight:bold;
background-color:yellow;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("input").keyup(function(){ 
        $("div").text($("input").val());

    });
});
</script>
</head>
<body>

Sample value: <input type="text">


<div></div>

</body>
</html>

5 个答案:

答案 0 :(得分:2)

您需要为此添加word-wrap: break-word;属性:

$(document).ready(function(){
    $("input").keyup(function(){ 
        $("div").text($("input").val());

    });
});
div {
max-width: 300px;
font-size:40px;
color:red;
font-weight:bold;
background-color:yellow;
word-wrap: break-word;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Sample value: <input type="text">


<div></div>

答案 1 :(得分:1)

您可以在div元素中使用css属性word-wrap:break-word;。它适用于所有浏览器。

word-break: break-all;

答案 2 :(得分:1)

您可以为min-width

设置min-heightword-wrapdiv

答案 3 :(得分:1)

看看这个小提琴max width property

HTML: -

Sample value: <input type="text">

JQuery: -

$(document).ready(function(){
$("input").keyup(function(){ 
    $("div").text($("input").val());

});

});

CSS: -

    div {
max-width: 300px;
font-size:40px;
color:red;
font-weight:bold;
background-color:yellow;
word-wrap : break-word;
}

答案 4 :(得分:1)

如果你想在行中显示值,只需将div的溢出设置为隐藏,如果要以多行显示值,只需将div的自动换行设置为break-word。

  

自动换行CSS属性用于指定浏览器是否允许在单词中断行,以防止在其他不可破坏的字符串太长而无法容纳时溢出。

     

overflow属性指定当它的块级容器太大时剪辑内容,渲染滚动条或显示溢出内容。