【发布时间】:2010-03-19 14:39:10
【问题描述】:
我正在尝试编写一个简单的基于 JavaScript 的模式对话框。 JavaScript 函数获取内容,将其放入新的 iframe 并将 iframe 添加到页面。到目前为止效果很好,唯一的问题是对话框的内容(例如表格)被包装了,尽管页面上有足够的空间。
我希望对话框的内容(在我的例子中是一个表格)使用尽可能多的空间,而不需要换行。我尝试了很多在 iframe 和表格上设置 width/style.width 的组合。什么都没有。
这里是显示 iframe 对话框的代码:
function SimpleDialog() {
this.domElement = document.createElement('iframe');
this.domElement.setAttribute('style', 'border: 1px solid red; z-index: 201; position: absolute; top: 0px; left: 0px;');
this.showWithContent = function(content) {
document.getElementsByTagName('body')[0].appendChild(this.domElement);
this.domElement.contentDocument.body.appendChild(content);
var contentBody = this.domElement.contentDocument.body;
contentBody.style.padding = '0px';
contentBody.style.margin = '0px';
// Set the iframe size to the size of content.
// However, content got wrapped already.
this.domElement.style.height = content.offsetHeight + 'px';
this.domElement.style.width = content.offsetWidth + 'px';
this._centerOnScreen();
};
this._centerOnScreen = function() {
this.domElement.style.left = window.pageXOffset + (window.innerWidth / 2) - (this.domElement.offsetWidth / 2) + 'px';
this.domElement.style.top = window.pageYOffset + (window.innerHeight / 2) - (this.domElement.offsetHeight / 2) + 'px';
};
}
这里是测试代码:
var table = document.createElement('table');
table.setAttribute('style', 'border: 1px solid black; width: 100%;');
table.innerHTML = "<tr><td style='font-size:40px;'>Hello world in big letters</td></tr><tr><td>second row</td></tr>";
var dialog = new SimpleDialog();
dialog.showWithContent(table);
表格很好地显示在页面的中心,但第一个单元格中的单词被换成了两行。如何让表格根据需要使用尽可能多的空间(不使用 white-space: nowrap ;)
提前感谢您的任何建议!
-马克
编辑:我首先使用 iframe 的原因是主页面的 CSS 样式不会影响对话框内的元素。例如,将文本颜色设置为红色的页面,但我希望对话框文本保持纯黑色。
【问题讨论】:
标签: javascript css iframe dialog