简体   繁体   中英

Loading image on website open

My index.html:

<body id="body" ng-app="myApp" ng-controller="Main" ng-init="init()">
</body>
<script src="app.js"></script>

My 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;
    };
}]);

My init() function definitely gets executed but I have no clue why my image doesn't get set on the body.. Any things I missed or overlooked?

No img tag shows up in the body

The reason is because the image isn't appended until it's loaded, but it also won't be loaded until it's appended. If you want to hide the image until it's done loading, try the following:

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

the problem is in your path. for example, if you put url to image, it works. see in this link: http://plnkr.co/edit/gSRn5v2otzYb0U5EPj8W?p=preview

now for your problem, I think you need to put this src:

 var path = "./images/image"+rand+".jpg";

or

 var path = "../images/image"+rand+".jpg";

it depends in your images folder and where it is in the folder tree. i guess it couldn't find the image in this path.

if none of them works so please show us what you get in the console log, it will help us to give you an answer.

hope I helped

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