我正在开发一个仅包含 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/