Javascript文档写覆盖页面?

栏目: CSS · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/4520440/javascript-document-write-overwriting-page
我是 javascript

的新手.

我正在尝试使用document.write(使用Wordpress)创建一个标记,以添加在预加载之前隐藏图像的样式.我不得不求助于编写Javascript样式来隐藏图像,然后才能通过CSS加载它们.我不想将其实际写入CSS文件,因为用户已禁用Javascript,然后图像将永远不会显示.

我正在尝试使用此代码:

jQuery(function($) {
    document.write('<style type="text/css"> .preload img { display: none; } </style>');
    $('#body-wrap').preloadThis();
});

但是,它只是覆盖整个页面并使其变为空白.我怎么能阻止这个?我想在不删除页面的情况下添加标签.尝试使用’返回’,没有运气.

对不起,我是新手.提前致谢.

在页面加载完 implicitly calls document.open()

之后使用document.write(),这将创建一个新页面.您通常应该避免使用document.write()并坚持使用正确的DOM创建技术,或者使用jQuery的简写创建方法:

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>在其他任何地方都无效,尽管所有浏览器都应该解析它.

翻译自:https://stackoverflow.com/questions/4520440/javascript-document-write-overwriting-page


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Head First HTML and CSS

Head First HTML and CSS

Elisabeth Robson、Eric Freeman / O'Reilly Media / 2012-9-8 / USD 39.99

Tired of reading HTML books that only make sense after you're an expert? Then it's about time you picked up Head First HTML and really learned HTML. You want to learn HTML so you can finally create th......一起来看看 《Head First HTML and CSS》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换