开发者

I can't assign a class to an element opened in new window

hi every body I'm trying to open an image in a new window ,using javascript, by clicking on a button, then set a class to the image, using this code:

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

and this is the internal style I have included in my code in a style tag: .larger{ width:10px; } and in the body tag 1:I have include my image source by an img tag 2:make a button tag with an onclick=larger() attribute

but unfortunately I have a problem with last sentence, the class is not assigned at all to the image. I have tried to use classname also instead of setttribute but it generates the same result. any ideas? thx


First, the code you wrote is wrong. There's an apostrophe too much behind img.

Second, you didn't assign an ID to your img element, so you can't access it with document.getElementById.

Use something like

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";


On a side note, you will also want to include in this new page some css otherwise this class="larger" will not do anything.

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>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜