javascript - 在页面加载和窗口调整大小时使用图像调整 div 大小

标签 javascript jquery

http://bm-translations.de的标题根据窗口宽度更改其高度,但有时当我加载页面时,它看起来像这样: enter image description here

这就是代码:

//navheader responsive height   
$(window).on('resize', function(){
    $("#banner").css("height",$('#navheader').height()+30);
}).trigger('resize'); //on page load

如何优化?

正如评论中所建议的那样,我尝试改为设置 CSS calc,但没有任何结果。我做错了什么?

我将父 #navigation 设置为 height:100% 并将 #banner 设置为

height: -moz-calc(100% + 30px);
height: -webkit-calc(100% + 30px);
height: calc(100% + 30px);

最佳答案

您应该使用 $( window ).on( "load", function() { ... }) 而不是只运行 $(window).trigger('resize' )在页面底部,如下:

$(window).on("load", function() {
     $(window).trigger('resize');
})

从以下链接可以看出: https://learn.jquery.com/using-jquery-core/document-ready/

A page can't be manipulated safely until the document is "ready." Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

由于您在导航中有图像,您应该等待整个页面加载以进行正确的 $('#navheader').height() 检测。

关于javascript - 在页面加载和窗口调整大小时使用图像调整 div 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45629497/

相关文章:

javascript - Angular : how to update non-angular javascript variable in response to a change of scope model?

javascript - 无法读取 null 的属性 'removeClass'

javascript - Object.prototype.isPrototypeOf 与 obj.prototype.isPrototypeOf

javascript - 如何从异步调用返回响应?

javascript - 如何在 jquery 中使两个计数器按钮相互独立?

javascript - 在 ng-view 加载或指令加载后运行 javascript

javascript - 字符串比较返回 false。 jQuery Mobile 的奇怪 JavaScript 行为

javascript - 去掉Scrollbars,根据Screensize展开div

jquery - 如何让CSS按钮显示透明

jquery - Bootstrap 3 : Collapse Accordion Not Working