Javascript .css()jquery工作不正常
我试图将窗口高度应用于特定div的最大高度Javascript .css()jquery工作不正常,javascript,jquery,css,Javascript,Jquery,Css,我试图将窗口高度应用于特定div的最大高度 $(document).ready(function(){ console.log('Initial Window height:', $(window).height()); $('.wordboard').css({ "max-height": ($(window).height()-150) + 'px' }); //console.log($('.wordboard').css({"max-hei
$(document).ready(function(){
console.log('Initial Window height:', $(window).height());
$('.wordboard').css({ "max-height": ($(window).height()-150) + 'px' });
//console.log($('.wordboard').css({"max-height": ($(window).height() - 150) + 'px'}));
console.log("Initial max height of $('.wordboard'): ", $('.wordboard').css("max-height"));
$(window).resize(function(){
$('.wordboard').css({ "max-height": ($('body').height()-150) + 'px' });
console.log("$('.wordboard').css('max-height')",$('.wordboard').css('max-height'));
});
});
但是,我的网站已加载:未应用最大高度。控制台中的结果是加载网站时:
Initial Window height: 550
script.js:28 Initial max height of $('.wordboard'): undefined
(After i resize the window, the effect is now apply. However, I want to apply as soon as the window is loaded)
script.js:31 $('.wordboard').css('max-height') 718px
script.js:31 $('.wordboard').css('max-height') 723px
script.js:31 $('.wordboard').css('max-height') 728px
script.js:31 $('.wordboard').css('max-height') 733px
这是正确的方法
$('.wordboard').css('max-height',"723px");
事件中有代码,
resize
事件
它将仅在触发该事件时执行。(如你所证实)
现在,您有两个选项:
调整大小事件:
$(窗口).resize(函数(){[…]}).resize()代码>
是的,只需在事件声明之后添加.resize()
。就这么简单李>
复制代码:
$(窗口).resize(函数(){[…]});
$('.wordboard').css({“最大高度”):($('body').height()-150)+'px'});
唯一的解决方案是,当您在document ready伪事件上调用代码段时,DOM中不存在您的元素。wordboard
。您肯定是在动态添加它(或插件)
编辑:只需检查它:
$(function(){console.log($(".wordboard").length);});
如果显示0
,您就知道问题的来源。为什么是这个固定数字?有什么特别的原因吗?这也是正确的$('.wordboard').css({“最大高度”:($(window.height()-150)+“px'});不知道这是怎么解决OP的问题的?!可能和“???px”没有用引号括起来有关。您能提供JSFIDLE复制您的问题吗?谢谢。这一定是问题所在。我只需要将脚本移到页面底部