После полудня,
Я сделал код для добавления изображений на страницу и пытался разобраться, как легко переключаться между изображениями? Вот код. Стоит ли здесь стоять в jquery? Я полный новичок, так жаль глупый вопрос, если это легко..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Adweek</title>
<style type="text/css">
* {
margin:0;
padding:0;
border:0;
}
html, body, iframe {
height:100%;
width:100%;
overflow:hidden;
}
</style>
<script type="text/javascript">
var pages = new Array(); //this will hold your pages
pages[0] = 'page1.html';
pages[1] = 'page2.html';
pages[2] = 'page3.html';
pages[3] = 'page4.html';
pages[4] = 'page5.html';
pages[5] = 'page6.html';
pages[6] = 'page7.html';
pages[7] = 'page8.html';
pages[8] = 'page9.html';
pages[9] = 'page10.html';
pages[10] = 'page11.html';
var time = 10; // set this to the time you want it to rotate in seconds // do not edit
var i = 1;
function setPage() {
if(i == pages.length){
i = 0;
}
document.getElementById('holder').setAttribute('src',pages[i]);
i++;
}
setInterval("setPage()",time * 1000); // do not edit
</script>
</head>
<body>
<iframe id="holder" src="page1.html" frameborder="0" scrolling="no"></iframe>
</body>
</html>
Чтобы плавно перейти к другому изображению, вам необходимо использовать следующую процедуру:
1) Загрузите новое изображение за изображение, которое вы хотите поменять. Выполняете ли вы это, загружая новое изображение в фоновом режиме в div или клонируя существующий элемент изображения.
2) Затухание текущего изображения. Это покажет изображение сзади.
3) Очистка - удалите любые избыточные элементы или css, которые вы создали на этом пути.
Пример скрипта - щелкните изображение, чтобы вызвать загрузку следующего.
Я прокомментировал код JS, надеясь, что он позволит вам изменить код в соответствии с вашими собственными целями.
JS
(function() {
"use strict";
function swapImage(newIndex, preload) {
var newImgSrc;
var $img = $imgContainer.find('img');
var imgIsAnimating = $img.is(':animated');
if (!imgIsAnimating) {
newImgSrc = images[newIndex];
// Set background-image to new image
$imgContainer.css({'background-image': 'url(' + newImgSrc + ')'});
//Set data-index to the new index value
$imgContainer.data('index', newIndex);
// Fade old image
$imgContainer.find('img').animate({ opacity: 0 }, function () {
//** Callback upon fade animation completed **/
imageSwapTidyUp(newImgSrc);
});
}
}
function imageSwapTidyUp(newImgSrc) {
var $img = $imgContainer.find('img');
// Change img src to new image
$img.prop('src', newImgSrc);
// Make img opaque
$img.animate({ opacity: 1 }, 100);
}
function addArrayNextIndexSupport() {
// Modify the Array object prototype, add nextIndex method
if (!Array.prototype.nextIndex) {
Array.prototype.nextIndex = function (currentIndex) {
// currentIndex + 1 if in bounds, else 0
return currentIndex < this.length - 1 ? currentIndex + 1 : 0;
}
}
}
//** On initialisation **//
// Array holding all the images to be loaded
var images = [
'http://s30.postimg.org/8877xxo69/image.jpg',
'http://s14.postimg.org/utnk4hm8h/image.jpg',
'http://s22.postimg.org/4cy006wbl/firecat.jpg',
'http://s27.postimg.org/456i0ge43/mad_baby.jpg'
];
var $imgContainer;
// Adds nextIndex to Array object
addArrayNextIndexSupport();
//** On DOM Ready **//
$(function () {
// Cache a reference to .img-container
$imgContainer = $('.img-container');
$imgContainer
.data('index', 0) // Set data-index to 0 on init
.on('click', function () {
var newIndex = images.nextIndex($(this).data('index'));
swapImage(newIndex);
});
});
}());
CSS
.img-container {
background-repeat: no-repeat;
background-position: top left;
width: 620px;
height: 465px;
}
.img-container img {
display: block;
}
HTML
<div class="img-container">
<img src="http://s30.postimg.org/8877xxo69/image.jpg" alt="">
</div>
(1 - opacity)
а затем следующее изображение с opacity
для серии изображений, но в некоторых местах оно потемнело. Вы должны установить фон на 100% непрозрачности, затем нарисуйте следующее изображение с (в моем случае) opacity = (percent / 100 * maxImgs) % 1
(где процент, как далеко вы находитесь, и maxImgs
, сколько изображений у вас есть Спасибо, что сэкономили мне много времени.
setInterval(function(){setPage()},time * 1000);
здесь: jsfiddle.net/754cm