Javascript文档覆盖页? [英] Javascript document write overwriting page?
问题描述
我是javascript的新手。
I'm very new with javascript.
我试图使用document.write(使用Wordpress)创建一个标签来添加一个隐藏图片的样式它们是预装的。我不得不求助于写一个Javascript样式来隐藏图像之前通过CSS加载。我不想实际写入到CSS文件中,用户已禁用Javascript,然后图像永远不会显示。
I'm trying to create a tag using document.write (with Wordpress) to add a style that hides images before they are preloaded. I've had to resort to writing a Javascript style to hide the images before they are loaded via CSS. I don't want to actually write it into the CSS file incase the user has Javascript disabled and then the images would never show.
我试图获取此代码工作:
I'm trying to get this code to work:
jQuery(function($) {
document.write('<style type="text/css"> .preload img { display: none; } </style>');
$('#body-wrap').preloadThis();
});
但是,它只是覆盖整个页面,使其变为空白。如何停止这个?我想将标记添加到而不删除页面。尝试使用return,没有运气。
But, it is just overwriting the whole page and making it go blank. How can I stop this? I want to add the tag to the without removing the page. Tried using 'return', no luck.
对不起,我是新手。提前感谢。
Sorry, I'm a novice. Thanks in advance.
推荐答案
使用 document.write()
页面已完成加载隐式调用 document.open()
,创建一个新页面。您应该通常避免 document.write()
并坚持适当的DOM创建技术,或使用jQuery的简写创建方法:
Using document.write()
after the page has finished loading implicitly calls document.open()
, which creates a new page. You should generally avoid document.write()
and stick to proper DOM creation techniques, or use jQuery's shorthand creation methods:
jQuery(function($) {
$('<style type="text/css"> .preload img { display: none; } </style>')
.appendTo("head");
$('#body-wrap').preloadThis();
});
假设您无法编辑HTML或CSS文件由页面加载以包括此规则?如果是这种情况,并且您希望在页面完成加载之前应用这些样式,请从jQuery ready处理程序中取
document.write()
:
// write() before the document finishes loading
document.write('<style type="text/css"> .preload img { display: none; } </style>');
jQuery(function($) {
$('#body-wrap').preloadThis();
});
这将写入< style>
标签紧跟在当前执行的< script>
标签之后。希望这是在你的< head>
元素中,因为< style>
应该以任何一种方式解析它。
This will write the <style>
tag immediately after the currently executing <script>
tag. Hopefully, this is in your <head>
element as <style>
is invalid anywhere else, although all browsers should parse it OK either way.
这篇关于Javascript文档覆盖页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!