在页面加载前运行 JavaScript 函数(设置合适大小的背景)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4000654/
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
Running JavaScript function before page load (setting background of appropriate size)
提问by kremuwa
I've got an image background which content I want to be always visible, no matter what is the user's resolution. Therefore, I want to be able to determine what is the resolution and set appropriate background image file before page loads, on the very beginning. Is it possible somehow?
我有一个图像背景,无论用户的分辨率如何,我都希望其内容始终可见。因此,我希望能够在页面加载之前确定分辨率并设置适当的背景图像文件,一开始。有可能吗?
回答by Marko
The earliest point at which you can run a Javascript function with access to the DOM (without waiting for page load) is by placing a <script>
tag right after the opening <body>
tag.
最早可以在访问 DOM 的情况下运行 Javascript 函数(无需等待页面加载)是<script>
在开始<body>
标记之后放置一个标记。
Scripts inside the <head>
will run before this occurs, but there won't be access to the elements on the page.
里面的脚本<head>
会在这发生之前运行,但不会访问页面上的元素。
Try this code
试试这个代码
<body>
<script type="text/javascript">
alert("Some elements shouldn't even be visible when this shows");
</script>
... rest of the page
</body>
See this examplewith some Gangsta Lipsumtext.
请参阅此示例,其中包含一些Gangsta Lipsum文本。
回答by Gopherkhan
Check this article on getting screen resolution in Javascript: http://andylangton.co.uk/articles/javascript/browser-screen-resolution/
检查这篇关于在 Javascript 中获取屏幕分辨率的文章:http: //andylangton.co.uk/articles/javascript/browser-screen-resolution/
Script tags execute inline if you don't do anything special to defer them (and deferring script execution is not supported on all browsers). This means a script tag nested just inside the body tag will be executed before the rest of the body loads. You could have your script detect the screen resolution and set the background image for the body right there.
如果您没有做任何特殊的事情来延迟脚本标签,脚本标签就会内联执行(并且并非所有浏览器都支持延迟脚本执行)。这意味着嵌套在 body 标签内的 script 标签将在其余的 body 加载之前执行。你可以让你的脚本检测屏幕分辨率并在那里设置身体的背景图像。
回答by M2tM
Using a JavaScript framework like MooToolsyou can utilize the DomReadyevent instead of onLoad (which waits for all image elements to load) you can fire an event when the page has loaded.
使用像MooTools这样的 JavaScript 框架,您可以利用DomReady事件而不是 onLoad(等待所有图像元素加载),您可以在页面加载时触发事件。
Alternatively with CSS you can position absolute top left and width:100% to win the day. :O
或者使用 CSS,您可以定位绝对左上角和宽度:100% 来赢得这一天。:O
回答by stevelove
I realize you're specifically asking about JavaScript, but there's a pretty decent technique for doing this with CSS(and optionally a little JavaScript) described at the CSS Tricks site.
我意识到您是专门询问 JavaScript,但是在 CSS Tricks 站点上描述了使用 CSS(以及可选的少量 JavaScript)来执行此操作的相当不错的技术。