我无法将类分配给在新窗口中打开的元素

时间:2010-08-01 10:58:39

标签: javascript

我想尝试在新窗口中打开图像,使用javascript,点击按钮,然后使用以下代码将类设置为图像:

    OpenWindow=window.open("", "newwin","height=100,width=1000"); 
    OpenWindow.document.write("<img id='img1' src='webfonts.jpg'>");
    OpenWindow.document.getElementById("img1").className = "larger";
    OpenWindow.document.close();

这是我在代码中包含在样式标记中的内部样式: .larger {width:10px; } 并在身体标签 1:我通过img标签包含了我的图像源 2:使用onclick = greater()属性制作一个按钮标签

但不幸的是我的最后一句话有问题,该类根本没有分配给图像。  我也尝试使用classname而不是setttribute,但它会产生相同的结果。 有任何想法吗? thx

2 个答案:

答案 0 :(得分:2)

首先,你写的代码是错误的。 img后面有一个撇号太多了。

其次,您没有为img元素分配ID,因此您无法使用document.getElementById访问它。

使用类似

的内容
var docHead = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'+
    'http://www.w3.org/TR/html4/strict.dtd">'+
    '<html><head><title>Test page</title>'+
    '<style type="text/css">'+
    '  .larger { width: 10px }'+
    '</style></head><body>';
var docFoot = '</body></html>';

OpenWindow=window.open("", "newwin", "height=100,width=1000");
OpenWindow.document.write(docHead);
OpenWindow.document.write('<img id="img1" src="webfonts.jpg">');
OpenWindow.document.write(docFoot);
OpenWindow.document.close();
OpenWindow.document.getElementById('img1').className = "larger";

答案 1 :(得分:0)

在旁注中,您还希望在此新页面中包含一些css,否则此类=“较大”将不会执行任何操作。

OpenWindow.document.write('<html><link href="css/style.css"/><body>');
OpenWindow.document.write('<img src="{source URL}" id="img1" class="larger" />');
OpenWindow.document.write('</body></html>');
相关问题