我的index.html:
<body id="body" ng-app="myApp" ng-controller="Main" ng-init="init()">
</body>
<script src="app.js"></script>
我的app.js:
var app = angular.module('myApp', []);
app.controller('Main', ['$scope',function($scope){
$scope.test = 'Hiiii!';
// Init background
$scope.init = function () {
var rand = Math.floor(Math.random() * 3) + 1
var path = "/images/image"+rand+".jpg";
var img = new Image();
var body = document.getElementById('body');
img.onload = function() {
body.appendChild(img);
};
img.src = path;
};
}]);
我的 init() 函数肯定会被执行,但我不知道为什么我的图像没有在主体上设置。我错过或忽略了什么?
正文中没有显示 img 标签
最佳答案
原因是因为图像在加载之前不会被附加,但在附加之前也不会被加载。如果您想隐藏图像直到加载完成,请尝试以下操作:
var img = new Image();
var body = document.getElementById('body');
img.src = path;
img.style.visibility = "hidden";
img.onload = function() {
img.style.visibility = "visible";
};
body.appendChild(img);
关于javascript - 在打开的网站上加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33598083/