JavaScript-为什么这段代码不起作用

JavaScript - Why is this code not working?

本文关键字:代码 不起作用 为什么 段代码 JavaScript-      更新时间:2024-02-09

我正在使用JavaScript和CSS,尝试使用iframe制作一个masic消息框。我希望文档的opacity0.4,并显示消息框。然而,这些都没有发生。我该怎么办?

我的JavaScript

function messageBox(text)
{
    document.style.opacity = 0.4;
    document.style.filter = 'alpha(opacity=40);';
    var box = document.createElement('iframe');
    box.setAttribute('id', 'msgBox');
}

我的CSS

 #msgBox
 {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    height: 250px;
    width: 350px;
    background-color: #CCC;
    margin: auto;
    z-index:9999;
    color:white;
    box-shadow:1px 1px 1px 1px #444;
}

http://jsfiddle.net/a4m9d/

function messageBox(text){
    document.body.style.opacity = 0.4;
    document.body.style.filter = 'alpha(opacity="40");';
    var box = document.createElement('iframe');
    box.id='msgBox';
    document.body.appendChild(box);
}

尽管我建议使用div而不是iframe,但为了性能和灵活性,

document没有style属性。只有元素具有样式,而document不是元素。

您希望以<body>为目标,请尝试使用document.body

function messageBox(text) {
    document.body.style.opacity = 0.4;
    document.body.style.filter = 'alpha(opacity="40");';
    var box = document.createElement('iframe');
    box.setAttribute('id', 'msgBox');
}

演示:http://jsfiddle.net/a4m9d/3/