我正在尝试编写一个简单的基于 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 样式不会影响对话框内的元素。例如,将文本颜色设置为红色的页面,但我希望对话框文本保持纯黑色。
最佳答案
您的表格设置为 100%,但 100% 是什么?在创建时,没有定义任何东西的宽度。如果您指定一个固定宽度(即,不是百分比),那么 content.offsetHeight 和 .offsetWidth 将有一些东西可以使用。
关于javascript - 获取 iframe 中的内容以根据需要使用尽可能多的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2478090/