简体   繁体   中英

Why isn't this javascript code working?

 var contentObj = getElementById("content"); var widthOfContent = screen.availWidth * 0.6; var cssContObjStr = "width:" + (screen.availWidth * 0.6) + ";"; contentObj.style = cssContObjStr; 
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Testing</title> </head> <body> <div id="content"></div> jdhkfahsd jksahd fklhasdk fhaskdhf kalsdhf klashdfk hasdkf haskd hfasdkjfhkjasdh fkjasdkfh asjdkhf khdskf jhaskdjh fkjasdhf kjsahd fkasbdkfbsadvn iweb fnilewalnfiwa ebnkjsdbv jdbalisd df sads da s fsd afds fasdf sadf asdf adsf asdf sdf <script type="text/javascript" src="javas.js"></script> </body> </html> 

I've saved the javascript file as javas.js on my pc. However, I'm trying to set the width as 60% of the screen width in pixels. This isn't working.

How can I manage this? And please, don't say "set it to width:60% ".

You have several syntax errors, here's a list of what's wrong:

  • You need to call document.getElementById()
  • +\\ isn't needed, that's an improperly formatted literal...but isn't not needed here anyway
  • The width is a property on style , just set it like I have below, make sure to include "px" on the end.

Overall, it should just be:

 var contentObj = document.getElementById("content"); var widthOfContent = screen.availWidth * 0.6; contentObj.style.width = widthOfContent + "px"; 
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Testing</title> </head> <body> <div id="content"></div> jdhkfahsd jksahd fklhasdk fhaskdhf kalsdhf klashdfk hasdkf haskd hfasdkjfhkjasdh fkjasdkfh asjdkhf khdskf jhaskdjh fkjasdhf kjsahd fkasbdkfbsadvn iweb fnilewalnfiwa ebnkjsdbv jdbalisd df sads da s fsd afds fasdf sadf asdf adsf asdf sdf <script type="text/javascript" src="javas.js"></script> </body> </html> 

Can you please try this?

var contentObj = document.getElementById("content");
var widthOfContent = screen.availWidth * 0.6;
var cssContObjStr = "width:" + (screen.availWidth * 0.6) + "%;";
contentObj.style.cssText = cssContObjStr;

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM