I was trying to change the src of an image element on reload. I came up with this code, but it is not working for me:
var images = ['hero-1.jpg', 'hero-2.jpg', 'hero-3.jpg', 'hero-4.jpg', 'hero-5.jpg', 'hero-6.jpg'];
$('#hero figure img[src="images/' + images[Math.floor(Math.random() * images.length)] + '"]').appendTo('#hero img');
HTML
<section id="hero">
<figure>
<img src="images/hero-1.jpg" alt="Hero">
</figure><!-- End figure -->
</section><!-- End section#hero -->
Images are placed inside the image map directly in the root.
Here's a small AngularJS-app that does what you want: http://jsfiddle.net/HB7LU/3276/
It contains a controller with an array with the img
urls, and a function that returns a random one of these urls:
function MyCtrl($scope) {
var images = [
'http://placehold.it/200x200',
'http://placekitten.com/200/300',
'http://www.lorempixum.com/400/300'
];
$scope.getRandomImage = function () {
var randIndex = ~~(Math.random() * images.length);
return images[randIndex];
};
}
This is used in an expression in the html:
<img ng-src="{{getRandomImage()}}">
Here the Angular directive ng-src is used, because it's not allowed to have angular expressions in a src attribute.
Might be a bit overkill to use angular though.
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.