重要:请继续阅读代码段下方的内容。
我正在使用输入框,我在其占位符中有一个文本。我希望文字缩小以适应div。但似乎我的字符串被切断了:
我在CSS中使用了font-size:1vw;
但它不起作用。所以,现在我使用的是JS代码。但它只有在我使用与我在占位符中使用的内容相同的div时才有效。
var divWidth = $('.theDiv').width();
var text = $('.text');
var fontSize = 12;
while (text.width() > divWidth)
text.css('font-size', fontSize -= 0.5);
text.css('display', 'inline');
/* latin-ext */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 300;
src: local('Lato Light'), local('Lato-Light'), url(http://fonts.gstatic.com/s/lato/v11/dPJ5r9gl3kK6ijoeP1IRsvY6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Lato';
font-style: normal;
font-weight: 300;
src: local('Lato Light'), local('Lato-Light'), url(http://fonts.gstatic.com/s/lato/v11/EsvMC5un3kjyUhB9ZEPPwg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
body {
background: hsl(184,65%,49%);
margin: 0;
font-family: 'Lato';
text-align: center;
color: #000;
}
input[type="text"], .theDiv {
width:100%;
max-width:320px;
background:#fff;
color:#333;
font-family: Lato;
padding: 25px 15px 25px 0;
display: inline-block;
text-transform: uppercase;
font-weight: 700;
border: 3px solid #333;
}
.theDiv{
white-space:nowrap;
}
::-webkit-input-placeholder{
text-align:center;
white-space:nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="theDiv">
<span class="text" style="display:none;">This sentence is too large to fit within the div. This sentence is too large to fit within the div his sentence is too large to fit within the div his sentence is too large to fit within the div</span>
</div>
<input class="text" type="text" placeholder="This sentence is too large to fit within the div. This sentence is too large to fit within the div his sentence is too large to fit within the div his sentence is too large to fit within the div" />
这就是我遇到问题的路线:
var divWidth = $('.theDiv').width();
因此,我不想获得div
的宽度,而是希望我的代码中只有input
标记,并获得JS中input
标记的宽度。我试过了:
var divWidth = $(input).width();
没有成功。