CSS 只有达到最大高度时才增加宽度
CSS increase width only if max-height reached
我想制作一个具有最大高度和初始宽度的 div 并且仅当内容达到最大高度值时才增加宽度?如果没有 JavaScript 是否可以做到这一点?
https://fiddle.jshell.net/zn77t0r1/
更新:
如果没有,如何用JS或jQuery轻松做到?
所以你必须知道你的 div 的高度是多少才能增加它的宽度。
类似
If (height >= max-height) //change width
只有 css 或 html 这是不可能的。
但是用 jQuery 做起来很容易,如果你不介意的话。
应该这样做:
//call function when page is loaded
$(document).ready(function(){
resizeWidth();
});
//call function when page is resized
$(window).resize(function(){
resizeWidth();
});
function resizeWidth(){
var maxHeight = 250; // your max-height in px
if ($('.container').height() >= maxHeight) {
$('.container').css('max-width', '400px');
}else {
$('.container').css('max-width', '200px');
}
}
如果您允许 jQuery,您可以这样做:
$(document).ready(resizeWidth()); //call function when page is loaded
$(window).resize(resizeWidth()); //call function when page is resized
function resizeWidth(){
var maxHeight = $('.container').eq(0).css('max-height');
maxHeight = maxHeight.split('px')[0];//remove px
var cWidth = $('.container').eq(0).width();
var currHeight = $('div.container')[0].scrollHeight;
while(maxHeight < currHeight)
{
cWidth += 100;
$('.container').eq(0).css('width', cWidth + 'px' );
currHeight = $('div.container')[0].scrollHeight;
}
}
只要文本高于 div 的 max-height
.
,该函数就会不断将宽度增加 100 像素
我想制作一个具有最大高度和初始宽度的 div 并且仅当内容达到最大高度值时才增加宽度?如果没有 JavaScript 是否可以做到这一点?
https://fiddle.jshell.net/zn77t0r1/
更新:
如果没有,如何用JS或jQuery轻松做到?
所以你必须知道你的 div 的高度是多少才能增加它的宽度。
类似
If (height >= max-height) //change width
只有 css 或 html 这是不可能的。 但是用 jQuery 做起来很容易,如果你不介意的话。
应该这样做:
//call function when page is loaded
$(document).ready(function(){
resizeWidth();
});
//call function when page is resized
$(window).resize(function(){
resizeWidth();
});
function resizeWidth(){
var maxHeight = 250; // your max-height in px
if ($('.container').height() >= maxHeight) {
$('.container').css('max-width', '400px');
}else {
$('.container').css('max-width', '200px');
}
}
如果您允许 jQuery,您可以这样做:
$(document).ready(resizeWidth()); //call function when page is loaded
$(window).resize(resizeWidth()); //call function when page is resized
function resizeWidth(){
var maxHeight = $('.container').eq(0).css('max-height');
maxHeight = maxHeight.split('px')[0];//remove px
var cWidth = $('.container').eq(0).width();
var currHeight = $('div.container')[0].scrollHeight;
while(maxHeight < currHeight)
{
cWidth += 100;
$('.container').eq(0).css('width', cWidth + 'px' );
currHeight = $('div.container')[0].scrollHeight;
}
}
只要文本高于 div 的 max-height
.