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

时间:2013-08-01 17:36:00

标签: 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;
}

1 个答案:

答案 0 :(得分:1)

正如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);
}

这应该是您的最佳选择。