使用内联 CSS 并调用 javascript 函数动态设置 div 高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13367161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set div height dynamically using inline CSS and invoking a javascript function
提问by sergserg
For my purposes, I need to set the div height as quickly as possible.
出于我的目的,我需要尽快设置 div 高度。
Using the document.ready()
event is not fast enough, so I want to set the inline CSS style of the div.
使用document.ready()
事件不够快,所以想设置div的内联CSS样式。
How can achieve something like this?
如何实现这样的目标?
<div id="map-container" style="height:javascript(getwindowheight)px;">
<div id="map">
</div>
</div>
function getwindowsheight() {
return window.height;
}
Any suggestions?
有什么建议?
回答by matsko
Since you want it to be dynamic, you will need to pay attention to the following events:
既然你希望它是动态的,你就需要注意以下事件:
- window resize
- window ready
- 调整窗口大小
- 窗口准备好
Set your HTML first:
首先设置你的 HTML:
<div id="map-container"></div>
And then inside your JavaScript, setup a function to detect those:
然后在你的 JavaScript 中,设置一个函数来检测那些:
var applyMapContainerHeight = function() {
var height = $(window).height();
$("#map-container").height(height);
};
document.ready(function() {
applyMapContainerHeight();
});
$(window).resize(function() {
applyMapContainerHeight();
});
回答by Robin V.
<div id="map-container">
<div id="map">
</div>
</div>
<script type="text/javascript">
document.getElementById("map-container").style.height= $(window).height() + "px";
</script>
回答by Adriano Carneiro
Provided that jQuery is script files are included in the very beginning of your HTML, place some scripting right after the div
declaration:
如果 jQuery 脚本文件包含在 HTML 的最开头,请在div
声明后立即放置一些脚本:
<div id="map-container">
<div id="map">
</div>
</div>
<script type="text/javascript">
$("#map-container").height(getwindowsheight());
function getwindowsheight() {
return window.height;
}
</script>
回答by Senad Me?kin
Then don't use document.ready
然后不要使用 document.ready
just execute your js after div
只需在 div 之后执行你的 js
<div id="map-container">
<div id="map">
</div>
</div>
<script type="text/javascript">
$('#map-container').css({ height: 'your height'});
</script>