javascript - 类选择器在 IE8 弹出窗口中不起作用,但 id 选择器会

标签 javascript css internet-explorer-8

我正在开发一个仅包含 img 元素的简单弹出窗口。一切正常,但我在使用 img 元素的类选择器时遇到了麻烦。问题是,如果我使用类选择器,IE8 不会将样式(例如,简单的边框)应用到弹出窗口中的 img 元素,但是,如果我它会应用样式使用 id 选择器。我错过了什么?还有其他人得到相同的结果吗?

javascript...

myWindow=window.open('','','width=450,height=800,scrollbars=yes,menubar=no,status=no,location=no,resizable=no,directories=no,toolbar=no');

// prepare pop-up window with basic html structure
myWindow.document.open();   // maybe unnecessary
myWindow.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">');
myWindow.document.write('<html><head><title>'+popupTitle+'</title>');
myWindow.document.write('<link rel="stylesheet" type="text/css" href="example.css"></script></head>');
myWindow.document.write('<body></body></html>');
myWindow.document.close();  // maybe unnecessary

var imgdiv = myWindow.document.createElement('div');
imgdiv.setAttribute('id','popupwindowdiv');
myWindow.document.body.appendChild(imgdiv);

// add image elements to the pop-up window
for ( var i=0; i < images.length; i++) {
    var addImage = myWindow.document.createElement('img');
    addImage.setAttribute('src',<imgurl from images array>);
    addImage.setAttribute('id','popupwindowimage'); // WILL WORK
    //addImage.setAttribute('class','popupwindowimage'); // <-- WON'T WORK IN IE8
    imgdiv.appendChild(addImage);
}
if (window.focus){ myWindow.focus(); }

还有CSS...

// works
#popupwindowimage{
    border-style:solid;
    border-width:1px;
    margin-bottom:10px;
}
// doesn't work
.popupwindowimage{
    border-style:solid;
    border-width:1px;
    margin-bottom:10px;
}

最佳答案

正如 Teemu 指出的那样,使用:

// add image elements to the pop-up window
for ( var i=0; i < images.length; i++) {
    var addImage = myWindow.document.createElement('img');
    addImage.setAttribute('src',<imgurl from images array>);
    //addImage.setAttribute('id','popupwindowimage'); // WILL WORK
    //addImage.setAttribute('class','popupwindowimage'); // <-- WON'T WORK IN IE8
    addItem.className += "popupwindowimage"; // <-- SHOULD WORK IN ALL BROWSERS
    imgdiv.appendChild(addImage);
}

这应该是您的最佳选择。

关于javascript - 类选择器在 IE8 弹出窗口中不起作用,但 id 选择器会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18000848/

相关文章:

javascript - 如何正确缩小 angularJS 文件

javascript - 网站可在除 Internet Explorer 8 以外的所有浏览器上运行

jquery - IE 8 加载站点时崩溃,无法调试 -

css - 在 Internet Explorer 7 中设置 div 高度时出现问题

html - 创建 Angular 彩色横幅

javascript - jQuery 在 IE8 中添加自闭合 DIV 标签

javascript - 保护 "private"类成员免遭修改

javascript - 单击指令 ng-repeat 项时如何切换 ng-class

javascript - 为什么 TypeScript 将 .default 添加到全局定义的导入中?

html - 使用 CSS 创建页面偏移