是否可以从onload方法返回值并在javascript中分配给变量?我有多个值从方法返回。我不想在html中打印(我知道如何打印),但我希望它分配给变量。
<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端的变量。
答案 0 :(得分:2)
不使用div的onload事件(不能在所有浏览器上工作),而是使用windows的onload事件
<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>
答案 1 :(得分:2)
我的建议
var scP = {
"sW":screen.width,
"sH":screen.height,
"saW":screen.availWidth,
"saC":screen.colorDepth,
"pixelDepth":screen.pixelDepth}
现在你可以使用
scP.sW
您需要的任何地方
例如:
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;
}
<div id="sprops"></div><br/>
<div>
sw: <span id="sw"></span>,
pd: <span id="pd"></span>
bla: <span id="bla"></span>
</div>