Слайд-шоу проблема со скриптом
Доброго времени суток, проблема со скриптом:
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8" /> <title>Документ без названия</title> <!-- <link href="style.css" rel="stylesheet" type="text/css" /> --> <style type="text/css"> .img1{ background-color:#7E6497; } .img2{ background-color:#D0FF00; } .img3{ background-color:#00C8FF; } .img4{ background-color:#001318; } #img{ width:200px; height:200px; margin:auto; margin-top: 8%; } </style> </head> <body> <div id='an'><header id="img" role="banner" style="background-position: 50% 18px;"></header></div> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"></script> <script> $(function(){ var imgMass = ['img1','img2','img3','img4']; var i = 0; var r = 0; var go = true; add(); // auto setTimeout(remove, 5000) // auto setTimeout(animat, 4000); // auto $('header[id=img]').hover(function(){ if(go){ return stopTimer(); } },function(){ if(!go){ return startTimer(); } }); function add(){ if(!go){ return; }else if(i == 4){ i = 0 } $('header[id=img]').addClass(imgMass[i]); i++; setTimeout(add,5000); }; function remove(){ if(!go){ return; }else if(r == 4){ r = 0 } $('header[id=img]').removeClass(imgMass[r]); r++; setTimeout(remove, 5000); }; function animat(){ if(!go){ return; } $('header[id=img]').animate({'opacity':'0'},1000).animate({'opacity':'1'},1000); setTimeout(animat,5000) }; function stopTimer(){ go = false; } function startTimer(){ go = true; setTimeout(add, 5000); setTimeout(remove, 5000); setTimeout(animat, 4000); } }) </script> </body> </html> Его идея помимо плавной смены изображений заключается в том, что при наведении на область картинок слайд-шоу останавливалась, а при уводе мышки продолжалась с того же места. И все бы ничего, но по факту слайд-шоу, до наведения работает так как и задумано, при наведении делает паузу как и задумано, но при уводе ускоряется раза в два, позже просто все таймеры сбиваются. Мне кажется, что проблема в setTimeout такое чувство, что после увода работают и таймер который был, до события hover() и после одновременно Вы как считаете в чем проблема? Каким образом исправить этот скрипт? И есть ли альтернатива? Заранее спасибо =) |
oleg901,
уберите параметр go, и прочитайте про clearTimeout |
oleg901,
Пожалуйста, отформатируйте свой код! Для этого его можно заключить в специальные теги: js/css/html и т.п., например: [js] ... ваш код... [/js] О том, как вставить в сообщение исполняемый javascript и html-код, а также о дополнительных возможностях форматирования - читайте http://javascript.ru/formatting. |
Цитата:
|
Цитата:
|
Цитата:
|
смена фона с opacity эффектом и пауза на hover
oleg901,
<!DOCTYPE html> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> .carousel{ width: 350px; height: 170px; position: relative; opacity: 0; border-radius: 8px; box-sizing: border-box; border: #8B4513 2px solid; transition: opacity .8s ease-in; background-size: 350px 170px; } .carousel.show{ opacity: 1; } .carousel.vertical{ width: 170px; height: 350px; background-size: 170px 350px; } </style> <script> window.addEventListener("DOMContentLoaded", function() { [].forEach.call(document.querySelectorAll(".carousel"), function(el) { var img = JSON.parse(el.dataset.src), len = img.length, i = len - 1, p = el.dataset.pause || 5E3, t; function g() { i = ++i % len; el.style.backgroundImage = "url(" + img[i] + ")"; el.classList.add("show"); t = window.setTimeout(k, p) } g(); function k() { el.classList.remove("show"); t = window.setTimeout(g, 800) } el.addEventListener('mouseenter', function() { window.clearTimeout(t); el.classList.add("show"); }); el.addEventListener('mouseleave', k) }) }); </script> </head> <body> <div class="carousel" data-pause="3000" data-src='[ "http://img-fotki.yandex.ru/get/5640/35900228.10c/0_7388e_3ab59b4a_XL.jpeg.jpg", "http://1.bp.blogspot.com/-aleHkBUuqOI/VY0HrCytsXI/AAAAAAAAq1g/f2emGtdqdWo/s640/2015-06-05_0145.jpg", "http://www.fotki.ykt.ru/albums/userpics/2013/11-18/1384739526_image.jpg"]'> </div> <div class="carousel vertical" data-pause="3000" data-src='[ "http://static.mnogonado.net/images/img.php?w=250&l=%2Fstore%2Fimage%2F800x600_qdv_57108c999ba0b1775c4bfe263023fb6a_1474795-404.png", "http://rugirlz.com/pics/hv_dp20088034.jpg" ]'> </div> </body> </html> |
Цитата:
|
oleg901,
не копируйте сообщения целиком, если в этом нет особой необходимости. |
слайдер и пауза jquery
oleg901,
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title>Документ без названия</title> <!-- <link href="style.css" rel="stylesheet" type="text/css" /> --> <style type="text/css"> .img1 { background-color: #7e6497; } .img2 { background-color: #d0ff00; } .img3 { background-color: #00c8ff; } .img4 { background-color: #001318; } #img { width: 200px; height: 200px; margin: auto; margin-top: 8%; } </style> <style type="text/css"> header.c1 { background-position: 50% 18px; } </style> </head> <body> <div id='an'> <header id="img" role="banner" class="c1"></header> </div> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"></script> <script> $(function() { var el = $("#img"); var imgMass = ["img1", "img2", "img3", "img4"]; var i = 0; el.addClass(imgMass[i]); function show() { el.delay(3000).animate({ "opacity": "0" }, 800); el.queue(function(next) { el.removeClass(imgMass[i]); i++; if (i == imgMass.length) i = 0; el.addClass(imgMass[i]); next() }); el.animate({ "opacity": "1" }, 800, show) } show(); el.hover(function() { el.stop(true, true).css({ "opacity": "1" }) }, show) }); </script> </body> </html> |
Часовой пояс GMT +3, время: 01:07. |