首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从onload方法返回值并赋值给变量

问从onload方法返回值并赋值给变量
EN

Stack Overflow用户
提问于 2016-02-10 05:57:49
回答 2查看 1.4K关注 0票数 2

可以从onload方法返回值并在javascript中为变量赋值吗?我有多个值要从方法返回。我不想在html中打印它(我知道如何打印),但是我想让它赋值给一个变量。

代码语言:javascript
复制
<html>

<div id="screenCapture" onload="screenProperties()">Screen properties</div>

<p id="sW"> <p>

</body>

<script type="text/javascript">
function screenProperties(){

    sW=screen.width;
    sH=screen.height;
    saW=screen.availWidth;
    saC=screen.colorDepth;
    pixelDepth=screen.pixelDepth;

return  "sw:"+sW+"sH:"+sH+"saW:"+saW+"saC:"+saC+"pixelDepth:"+pixelDepth;

}
alert(screenProperties());
</script>

</html>

是我的方法。在这里,我希望将返回的值赋值给html端的一个变量。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-10 06:12:29

我的建议

代码语言:javascript
复制
var scP = {
 "sW":screen.width,
 "sH":screen.height,
 "saW":screen.availWidth,
 "saC":screen.colorDepth,
 "pixelDepth":screen.pixelDepth}

现在你可以用

代码语言:javascript
复制
scP.sW 

任何你需要的地方

例如:

​

代码语言:javascript
复制
var scP = {
  "sW": screen.width             || "not available",
  "sH": screen.height            || "not available",
  "saW": screen.availWidth       || "not available",
  "saC": screen.colorDepth       || "not available",
  "pixelDepth": screen.pixelDepth|| "not available",
  "bla": screen.bla              || "not available"
}

window.onload = function() {
    // need window.onload to wait for sprops div to render
    document.getElementById("sprops").innerHTML = JSON.stringify(scP); // all
    document.getElementById("pd").innerHTML = scP.pixelDepth;
    document.getElementById("sw").innerHTML = scP.sW;
    document.getElementById("bla").innerHTML = scP.bla;
}
代码语言:javascript
复制
<div id="sprops"></div><br/>
<div>
  sw: <span id="sw"></span>, 
  pd: <span id="pd"></span>
  bla: <span id="bla"></span>
</div>

​

票数 2
EN

Stack Overflow用户

发布于 2016-02-10 06:06:22

不要对div使用onload事件(并非在所有浏览器上都有效),而是使用windows的onload事件

代码语言:javascript
复制
<script>
  document.addEventListener("load", function(event) {
    screenProperties();
  });
  var sW,sH,saW,saC,pixelDepth;
  function screenProperties()
  {
    sW=screen.width;
    sH=screen.height;
    saW=screen.availWidth;
    saC=screen.colorDepth;
    pixelDepth=screen.pixelDepth;
  }
</script>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35307900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档