繁体   English   中英

使用 jQuery 或 Javascript 自动设置最小高度

[英]Setting min-height automatically with jQuery or Javascript

我想使用脚本根据实际元素的高度将 min-height 或 max-height 添加到元素。

所以我得到了 div 的.height() (?),然后使用该值来设置最小/最大高度。 这可能吗? 它必须是动态的,以便 div 可以更改高度但仍然具有正确的最小高度或最大高度。

我什么都没试过,只是搜索了如何去做——我真的不是 jQuery og Javascript 方面的专家。 我现在正在做的事情是使用 console.log 给我一个元素的高度(例如一个英雄部分),这样我就不需要在开发人员中手动检查它。 然后我将值写为 CSS 中的最小高度。 我这样做的原因是因为新的 Lighthouse Core Web Vitals (Cumulative Layout Shift (CLS))。

编辑:所以我想我找到了解决方案,并且(就像我说的)我不是这里的专家,但非常感谢任何反馈。

jQuery(".hero").css("min-height", function(){ 
  return jQuery(".hero").height();
});

这是你想要的一个例子

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Set a DIV height</title>
<style>
    .box{
        background: #f2f2f2;
        border: 1px solid #ccc;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){

        var newHeight = $(".input-height").val();
        $(".box").height(newHeight);

});
</script>
</head> 
<body>
    <form>
        <input type="text" class="input-height">
        <button type="button" class="set-height-btn">Set Height</button>
        <p>Enter the value in input box either as number (e.g. 100, 200) or combination of number and unit (e.g. 100%, 200px, 50em, auto) and click the "Set Height" button.</p>
    </form>
    <br>
    <div class="box">This is simple DIV box</div>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM