在CSS完全加载后运行Javascript
Running Javascript after CSS is fully loaded
我有一些代码取决于加载的css
我在页眉上加载css,然后在页脚上加载javascript
我用$(document).ready
尝试了javascript
$(document).ready(function() {
var bar_position, width;
bar_position = $('body').height() - 38;
width = $('body').width();
console.log(bar_position);
if (width <= 480) {
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
我试过$(window).ready
、$(window).load
,但都失败了。
您的代码真的很糟糕(除非您使用的是CoffeeScript)
$(function () {
bar_position = $('body').height() - 38; //38 is the size of the bar
width = $('body').width();
console.log(bar_position);
if (width <= 480) { //480 is the mobile width
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
CSS被加载在页眉中,JS被加载在页脚中,并被包装在文档中,在JS代码执行之前,你应该可以应用CSS。我猜元素没有宽度的原因是它是display: none;
,或者只包含浮动元素,或者类似的东西。换句话说,我认为这是一个CSS问题,而不是JS时间问题。试着进入你的Firebug/Chrome控制台,选择有问题的元素,并获取其宽度。
JavaScript注释不是#
,而是//
错误
bar_position = $('body').height() - 38 #38 is the size of the bar
右侧
bar_position = $('body').height() - 38 //38 is the size of the bar
还有一堆其他错误,代码无法运行。猜测您错过了一个标记,这不是纯JavaScript,因为它是块范围缩进的,到处都缺少大括号/闭包。
就绪事件就足够了。
当使用依赖于CSS样式属性值的脚本时,引用外部样式表或嵌入样式很重要元素,然后再引用脚本。
在代码依赖于加载的资产的情况下(例如,如果图像的尺寸是必需的),代码应该放在加载事件的处理程序。
此外,您的javascript无效。如果它应该是CoffeeScript,则您缺少->:
$(document).ready ->
bar_position = $('body').height() - 38 #38 is the size of the bar
width = $('body').width()
console.log(bar_position)
if (width <= 480) #480 is the mobile width
console.log("Entered");
$('#accounts-bar').css("top", bar_position)
return
如果它应该是JavaScript,那么您会遇到更多问题:
$(document).ready(function(){
bar_position = $('body').height() - 38; //38 is the size of the bar
width = $('body').width();
console.log(bar_position);
if (width <= 480) //480 is the mobile width {
console.log("Entered");
$('#accounts-bar').css("top", bar_position);
}
});
$(window).bind("load", function() {
// code here
});
相关文章:
- 在终端中运行 JavaScript 时(使用 rhino),如何使用 print() 函数在一行中打印
- 向下滚动时运行javascript
- 在Android WebView中运行Javascript-onPageFinished循环
- 在父网页的iframe中运行JavaScript
- 有条件地运行javascript函数-Razor,HTML
- 如何通过获取用户输入和使用按钮来运行JavaScript函数
- 使用c#在Web服务器上运行JavaScript方法
- 单击链接时停止运行javascript
- 在浏览器检查表单之前运行javascript onsubmit
- 如何在表单提交事件后运行JavaScript*
- Mediawiki小部件将不会运行javascript
- 有没有一种方法可以在服务器端页面加载之前在加载时运行javascript
- 在GitHub上运行JavaScript Koans
- Chrome扩展:是否有一种方法可以运行JavaScript来获取页面上的内部html,并将其保存到扩展中的变量中
- 在不加载页面的情况下运行javascript
- [AutoIt]如何使用FF.au3在FireFox上的页面中运行javascript
- 仅在屏幕媒体上运行javascript/jquery,而不是打印
- Scala提升了如何运行javascript函数并将返回值存储在变量中
- 安卓系统:通过loadUrl运行javascript时,网络视图中的视频会冻结
- 在页面加载完成之前,使用URL参数运行JavaScript