如何在悬停时暂停滑块?
How can I pause slider on hover?
我有一个 API 小型学习项目。在我通过调用 API 获取图像的地方,然后我 select 一些图像以在选定的时间间隔内创建幻灯片。
现在 我想在鼠标悬停(悬停)时暂停幻灯片。 但我不知道该怎么做。如果你们能帮助我。那将是非常棒的。下面是我的代码。
我的现场 link :https://muradtheoz.github.io/fancy-slider/
我的回购 link:github repo
下面是我的行代码
const imagesArea = document.querySelector('.images');
const gallery = document.querySelector('.gallery');
const galleryHeader = document.querySelector('.gallery-header');
const searchBtn = document.getElementById('search-btn');
const sliderBtn = document.getElementById('create-slider');
const sliderContainer = document.getElementById('sliders');
const inputField = document.getElementById('search');
const durationField = document.getElementById('duration');
// selected image
let sliders = [];
// If this key doesn't work
// Find the name in the url and go to their website
// to create your own api key
const KEY = '15674931-a9d714b6e9d654524df198e00&q';
// show images
const showImages = (images) => {
imagesArea.style.display = 'block';
gallery.innerHTML = '';
// show gallery title
galleryHeader.style.display = 'flex';
images.forEach(image => {
let div = document.createElement('div');
div.className = 'col-lg-3 col-md-4 col-xs-6 img-item mb-2';
div.innerHTML = ` <img class="img-fluid img-effect img-thumbnail" onclick=selectItem(event,"${image.webformatURL}") src="${image.webformatURL}" alt="${image.tags}">`;
gallery.appendChild(div);
})
toggleSpinner();
}
const getImages = (query) => {
toggleSpinner();
dangerInfo(false);
imagesArea.style.display = 'none';
const url = (`https://pixabay.com/api/?key=${KEY}=${query}&image_type=photo&pretty=true`);
fetch(url)
.then(response => response.json())
.then(data => {
if ((data.hits).length > 0) {
showImages(data.hits);
}
else {
imagesArea.style.display = 'none';
dangerInfo(true);
toggleSpinner();
}
})
.catch(err => dangerInfo(true))
}
let slideIndex = 0;
const selectItem = (event, img) => {
let element = event.target;
element.classList.add('added');
element.classList.remove('img-effect')
let item = sliders.indexOf(img);
if (item === -1) {
sliders.push(img);
} else {
// sliders.pop(img);
sliders.splice(item, 1);
element.classList.toggle("added");
element.classList.toggle('img-effect')
}
}
var timer
const createSlider = () => {
// check slider image length
if (sliders.length < 2) {
alert('Select at least 2 image.')
return;
}
// crate slider previous next area
sliderContainer.innerHTML = '';
const prevNext = document.createElement('div');
prevNext.className = "prev-next d-flex w-100 justify-content-between align-items-center";
prevNext.innerHTML = `
<span class="prev" onclick="changeItem(-1)"><i class="fas fa-chevron-left"></i></span>
<span class="next" onclick="changeItem(1)"><i class="fas fa-chevron-right"></i></span>
`;
sliderContainer.appendChild(prevNext)
document.querySelector('.main').style.display = 'block';
// hide image aria
imagesArea.style.display = 'none';
let duration = document.getElementById('duration').value || 1000;
if (duration <= 400) {
duration = 1000;
if (confirm("slider duration will set to 1s default")) {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(function () {
slideIndex++;
changeSlide(slideIndex);
}, duration);
}
else {
imagesArea.style.display = 'block';
}
}
else {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(function () {
slideIndex++;
changeSlide(slideIndex);
}, duration);
}
}
// change slider index
const changeItem = index => {
changeSlide(slideIndex += index);
}
// change slide item
const changeSlide = (index) => {
const items = document.querySelectorAll('.slider-item');
if (index < 0) {
slideIndex = items.length - 1
index = slideIndex;
};
if (index >= items.length) {
index = 0;
slideIndex = 0;
}
items.forEach(item => {
item.style.display = "none"
})
items[index].style.display = "block"
}
function getInputValue() {
document.querySelector('.main').style.display = 'none';
clearInterval(timer);
const search = document.getElementById('search');
getImages(search.value)
sliders.length = 0;
}
const triggerSearchBtn = inputField.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
getInputValue();
}
})
durationField.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
createSlider()
}
})
//Bonus Marking javascript
const toggleSpinner = () => {
const spinner = document.getElementById('spinner');
spinner.classList.toggle('d-flex');
}
const dangerInfo = (show) => {
const error = document.getElementById('error');
if (show) {
error.classList.add('d-flex');
}
else {
error.classList.remove('d-flex');
}
}
sliderContainer.addEventListener('mouseenter', e => {
e.target.style.display = "block";
});
sliderContainer.addEventListener('mouseleave', e => {
sliderContainer.style.border = '6px solid #1e1743';
});
#sliders {
height: 400px;
width: 60%;
overflow: hidden;
margin: 0 auto;
position: relative;
}
.gallery-header {
display: none;
}
.slider-item {
display: none;
}
.img-thumbnail {
cursor: pointer;
}
.added {
border: 2px solid #1e1743;
border-radius: 5px;
}
img {
height: 400px;
object-fit: cover;
}
.prev-next {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
cursor: pointer;
}
.prev, .next {
background-color: transparent;
padding: 8px 10px;
color: #fff;
}
.dot {
background-color: rgb(163, 156, 156);
height: 10px;
width: 10px;
border-radius: 50%;
cursor: pointer;
margin: 0 3px;
}
.main {
display: none;
}
/*bonus css style*/
.img-effect:hover{
background-color: #1e1743;
}
/*input arrow hide style*/
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
/* .slider-item :hover{
display: none;
} */
@media (max-width: 767px) {
.justify-content-around.align-items-center.mt-3.gallery-header.mb-2 {
flex-direction: column;
}
#sliders {
height: 300px;
width: 90%;
}
}
<!doctype html>
<html lang="en">
<head>
<title>Slide your favorite images</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css"
integrity="sha384-O8whS3fhG2OnA5Kas0Y9l3cfpmYjapjI0E4theH4iuMD+pLhbf6JI0jIMfYcK3yZ" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h4 class="mt-2 text-center">Search Image for create slider</h4>
<div class="form-inline mt-3 d-flex justify-content-center">
<div class="input-group col-md-6 mb-2">
<input type="text" class="form-control" id="search" placeholder="nature">
</div>
<button onclick="getInputValue()" type="button" id="search-btn" class="btn btn-primary mb-2">Search</button>
</div>
<!--bonus content-->
</div>
<div id="spinner" class="justify-content-center p-2 d-none">
<div class="spinner-border text-info" role="status">
<span class="visually-hidden"> </span>
</div>
</div>
<div id="error" class="justify-content-center p-2 d-none">
<div class="card text-white bg-danger mb-3" style="max-width: 18rem;">
<div class="card-header text-center">We Are sorry</div>
<div class="card-body">
<p class="card-text">The image your searching is not available</p>
</div>
</div>
</div>
<section class="images">
<div class="justify-content-around align-items-center mt-3 gallery-header mb-2">
<h3 class="head-title text-center">Select image for create slider</h3>
<div class="input-group col-md-3 mb-2 mb-md-0">
<input type="number" class="form-control arrow-hide" id="duration" placeholder="slider change duration">
</div>
<button onclick=" createSlider()" id="create-slider" class="btn btn-primary px-5">Create slider</button>
</div>
<div class="row gallery">
</section>
<!-- slider -->
<div class="main">
<section class="mt-5" id="sliders">
</section>
<div class="dots d-flex mt-2 w-100 justify-content-center align-items-center bg-light">
<span class="dot" onclick="changeItem(-1)"></span>
<span class="dot" onclick="changeItem(1)"></span>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<script src="./app.js"></script>
</body>
</html>
您的 app.js 的以下版本可以解决问题。
const imagesArea = document.querySelector('.images');
const gallery = document.querySelector('.gallery');
const galleryHeader = document.querySelector('.gallery-header');
const searchBtn = document.getElementById('search-btn');
const sliderBtn = document.getElementById('create-slider');
const sliderContainer = document.getElementById('sliders');
const inputField = document.getElementById('search');
// selected image
let sliders = [];
// Initial value
let lastSetDuration = 0;
// If this key doesn't work
// Find the name in the url and go to their website
// to create your own api key
const KEY = '15674931-a9d714b6e9d654524df198e00&q';
// show images
const showImages = (images) => {
imagesArea.style.display = 'block';
gallery.innerHTML = '';
// show gallery title
galleryHeader.style.display = 'flex';
images.forEach(image => {
let div = document.createElement('div');
div.className = 'col-lg-3 col-md-4 col-xs-6 img-item mb-2';
div.innerHTML = ` <img class="img-fluid img-effect img-thumbnail" onclick=selectItem(event,"${image.webformatURL}") src="${image.webformatURL}" alt="${image.tags}">`;
gallery.appendChild(div);
})
toggleSpinner();
}
const getImages = (query) => {
toggleSpinner();
dangerInfo(false);
imagesArea.style.display = 'none';
const url = (`https://pixabay.com/api/?key=${KEY}=${query}&image_type=photo&pretty=true`);
fetch(url)
.then(response => response.json())
.then(data => {
if ((data.hits).length > 0) {
showImages(data.hits);
}
else {
imagesArea.style.display = 'none';
dangerInfo(true);
toggleSpinner();
}
})
.catch(err => dangerInfo(true))
}
let slideIndex = 0;
const selectItem = (event, img) => {
let element = event.target;
element.classList.add('added');
element.classList.remove('img-effect')
let item = sliders.indexOf(img);
if (item === -1) {
sliders.push(img);
} else {
// sliders.pop(img);
sliders.splice(item, 1);
element.classList.toggle("added");
element.classList.toggle('img-effect')
}
}
var timer
const createSlider = () => {
// check slider image length
if (sliders.length < 2) {
alert('Select at least 2 image.')
return;
}
// crate slider previous next area
sliderContainer.innerHTML = '';
const prevNext = document.createElement('div');
prevNext.className = "prev-next d-flex w-100 justify-content-between align-items-center";
prevNext.innerHTML = `
<span class="prev" onclick="changeItem(-1)"><i class="fas fa-chevron-left"></i></span>
<span class="next" onclick="changeItem(1)"><i class="fas fa-chevron-right"></i></span>
`;
sliderContainer.appendChild(prevNext)
document.querySelector('.main').style.display = 'block';
// hide image aria
imagesArea.style.display = 'none';
let duration = document.getElementById('duration').value || 1000;
if (duration <= 400) {
duration = 1000;
if (confirm("slider duration will set to 1s default")) {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(sliderMoverCallback, duration);
lastSetDuration = duration;
}
else {
imagesArea.style.display = 'block';
}
}
else {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(sliderMoverCallback, duration);
lastSetDuration = duration;
}
}
const sliderMoverCallback = () => {
changeSlide(++slideIndex);
}
// change slider index
const changeItem = index => {
changeSlide(slideIndex += index);
}
// change slide item
const changeSlide = (index) => {
const items = document.querySelectorAll('.slider-item');
if (index < 0) {
slideIndex = items.length - 1
index = slideIndex;
};
if (index >= items.length) {
index = 0;
slideIndex = 0;
}
items.forEach(item => {
item.style.display = "none"
})
items[index].style.display = "block"
}
function getInputValue() {
document.querySelector('.main').style.display = 'none';
clearInterval(timer);
const search = document.getElementById('search');
getImages(search.value)
sliders.length = 0;
}
const triggerSearchBtn = inputField.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
getInputValue();
}
})
sliderBtn.addEventListener('click', function () {
createSlider()
})
sliderContainer.addEventListener('mouseover', () => {
clearInterval(timer);
timer = undefined;
})
sliderContainer.addEventListener('mouseout', () => {
if (timer === undefined) { // if no animation is performing now then start it
timer = setInterval(sliderMoverCallback, lastSetDuration)
}
})
//Bonus Marking javascript
const toggleSpinner = () => {
const spinner = document.getElementById('spinner');
spinner.classList.toggle('d-flex');
}
const dangerInfo = (show) => {
const error = document.getElementById('error');
if (show) {
error.classList.add('d-flex');
}
else {
error.classList.remove('d-flex');
}
}
P.S。我肯定会做一些重构。很难阅读和找到你需要的东西。
我有一个 API 小型学习项目。在我通过调用 API 获取图像的地方,然后我 select 一些图像以在选定的时间间隔内创建幻灯片。 现在 我想在鼠标悬停(悬停)时暂停幻灯片。 但我不知道该怎么做。如果你们能帮助我。那将是非常棒的。下面是我的代码。 我的现场 link :https://muradtheoz.github.io/fancy-slider/ 我的回购 link:github repo 下面是我的行代码
const imagesArea = document.querySelector('.images');
const gallery = document.querySelector('.gallery');
const galleryHeader = document.querySelector('.gallery-header');
const searchBtn = document.getElementById('search-btn');
const sliderBtn = document.getElementById('create-slider');
const sliderContainer = document.getElementById('sliders');
const inputField = document.getElementById('search');
const durationField = document.getElementById('duration');
// selected image
let sliders = [];
// If this key doesn't work
// Find the name in the url and go to their website
// to create your own api key
const KEY = '15674931-a9d714b6e9d654524df198e00&q';
// show images
const showImages = (images) => {
imagesArea.style.display = 'block';
gallery.innerHTML = '';
// show gallery title
galleryHeader.style.display = 'flex';
images.forEach(image => {
let div = document.createElement('div');
div.className = 'col-lg-3 col-md-4 col-xs-6 img-item mb-2';
div.innerHTML = ` <img class="img-fluid img-effect img-thumbnail" onclick=selectItem(event,"${image.webformatURL}") src="${image.webformatURL}" alt="${image.tags}">`;
gallery.appendChild(div);
})
toggleSpinner();
}
const getImages = (query) => {
toggleSpinner();
dangerInfo(false);
imagesArea.style.display = 'none';
const url = (`https://pixabay.com/api/?key=${KEY}=${query}&image_type=photo&pretty=true`);
fetch(url)
.then(response => response.json())
.then(data => {
if ((data.hits).length > 0) {
showImages(data.hits);
}
else {
imagesArea.style.display = 'none';
dangerInfo(true);
toggleSpinner();
}
})
.catch(err => dangerInfo(true))
}
let slideIndex = 0;
const selectItem = (event, img) => {
let element = event.target;
element.classList.add('added');
element.classList.remove('img-effect')
let item = sliders.indexOf(img);
if (item === -1) {
sliders.push(img);
} else {
// sliders.pop(img);
sliders.splice(item, 1);
element.classList.toggle("added");
element.classList.toggle('img-effect')
}
}
var timer
const createSlider = () => {
// check slider image length
if (sliders.length < 2) {
alert('Select at least 2 image.')
return;
}
// crate slider previous next area
sliderContainer.innerHTML = '';
const prevNext = document.createElement('div');
prevNext.className = "prev-next d-flex w-100 justify-content-between align-items-center";
prevNext.innerHTML = `
<span class="prev" onclick="changeItem(-1)"><i class="fas fa-chevron-left"></i></span>
<span class="next" onclick="changeItem(1)"><i class="fas fa-chevron-right"></i></span>
`;
sliderContainer.appendChild(prevNext)
document.querySelector('.main').style.display = 'block';
// hide image aria
imagesArea.style.display = 'none';
let duration = document.getElementById('duration').value || 1000;
if (duration <= 400) {
duration = 1000;
if (confirm("slider duration will set to 1s default")) {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(function () {
slideIndex++;
changeSlide(slideIndex);
}, duration);
}
else {
imagesArea.style.display = 'block';
}
}
else {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(function () {
slideIndex++;
changeSlide(slideIndex);
}, duration);
}
}
// change slider index
const changeItem = index => {
changeSlide(slideIndex += index);
}
// change slide item
const changeSlide = (index) => {
const items = document.querySelectorAll('.slider-item');
if (index < 0) {
slideIndex = items.length - 1
index = slideIndex;
};
if (index >= items.length) {
index = 0;
slideIndex = 0;
}
items.forEach(item => {
item.style.display = "none"
})
items[index].style.display = "block"
}
function getInputValue() {
document.querySelector('.main').style.display = 'none';
clearInterval(timer);
const search = document.getElementById('search');
getImages(search.value)
sliders.length = 0;
}
const triggerSearchBtn = inputField.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
getInputValue();
}
})
durationField.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
createSlider()
}
})
//Bonus Marking javascript
const toggleSpinner = () => {
const spinner = document.getElementById('spinner');
spinner.classList.toggle('d-flex');
}
const dangerInfo = (show) => {
const error = document.getElementById('error');
if (show) {
error.classList.add('d-flex');
}
else {
error.classList.remove('d-flex');
}
}
sliderContainer.addEventListener('mouseenter', e => {
e.target.style.display = "block";
});
sliderContainer.addEventListener('mouseleave', e => {
sliderContainer.style.border = '6px solid #1e1743';
});
#sliders {
height: 400px;
width: 60%;
overflow: hidden;
margin: 0 auto;
position: relative;
}
.gallery-header {
display: none;
}
.slider-item {
display: none;
}
.img-thumbnail {
cursor: pointer;
}
.added {
border: 2px solid #1e1743;
border-radius: 5px;
}
img {
height: 400px;
object-fit: cover;
}
.prev-next {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
cursor: pointer;
}
.prev, .next {
background-color: transparent;
padding: 8px 10px;
color: #fff;
}
.dot {
background-color: rgb(163, 156, 156);
height: 10px;
width: 10px;
border-radius: 50%;
cursor: pointer;
margin: 0 3px;
}
.main {
display: none;
}
/*bonus css style*/
.img-effect:hover{
background-color: #1e1743;
}
/*input arrow hide style*/
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
/* .slider-item :hover{
display: none;
} */
@media (max-width: 767px) {
.justify-content-around.align-items-center.mt-3.gallery-header.mb-2 {
flex-direction: column;
}
#sliders {
height: 300px;
width: 90%;
}
}
<!doctype html>
<html lang="en">
<head>
<title>Slide your favorite images</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css"
integrity="sha384-O8whS3fhG2OnA5Kas0Y9l3cfpmYjapjI0E4theH4iuMD+pLhbf6JI0jIMfYcK3yZ" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h4 class="mt-2 text-center">Search Image for create slider</h4>
<div class="form-inline mt-3 d-flex justify-content-center">
<div class="input-group col-md-6 mb-2">
<input type="text" class="form-control" id="search" placeholder="nature">
</div>
<button onclick="getInputValue()" type="button" id="search-btn" class="btn btn-primary mb-2">Search</button>
</div>
<!--bonus content-->
</div>
<div id="spinner" class="justify-content-center p-2 d-none">
<div class="spinner-border text-info" role="status">
<span class="visually-hidden"> </span>
</div>
</div>
<div id="error" class="justify-content-center p-2 d-none">
<div class="card text-white bg-danger mb-3" style="max-width: 18rem;">
<div class="card-header text-center">We Are sorry</div>
<div class="card-body">
<p class="card-text">The image your searching is not available</p>
</div>
</div>
</div>
<section class="images">
<div class="justify-content-around align-items-center mt-3 gallery-header mb-2">
<h3 class="head-title text-center">Select image for create slider</h3>
<div class="input-group col-md-3 mb-2 mb-md-0">
<input type="number" class="form-control arrow-hide" id="duration" placeholder="slider change duration">
</div>
<button onclick=" createSlider()" id="create-slider" class="btn btn-primary px-5">Create slider</button>
</div>
<div class="row gallery">
</section>
<!-- slider -->
<div class="main">
<section class="mt-5" id="sliders">
</section>
<div class="dots d-flex mt-2 w-100 justify-content-center align-items-center bg-light">
<span class="dot" onclick="changeItem(-1)"></span>
<span class="dot" onclick="changeItem(1)"></span>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<script src="./app.js"></script>
</body>
</html>
您的 app.js 的以下版本可以解决问题。
const imagesArea = document.querySelector('.images');
const gallery = document.querySelector('.gallery');
const galleryHeader = document.querySelector('.gallery-header');
const searchBtn = document.getElementById('search-btn');
const sliderBtn = document.getElementById('create-slider');
const sliderContainer = document.getElementById('sliders');
const inputField = document.getElementById('search');
// selected image
let sliders = [];
// Initial value
let lastSetDuration = 0;
// If this key doesn't work
// Find the name in the url and go to their website
// to create your own api key
const KEY = '15674931-a9d714b6e9d654524df198e00&q';
// show images
const showImages = (images) => {
imagesArea.style.display = 'block';
gallery.innerHTML = '';
// show gallery title
galleryHeader.style.display = 'flex';
images.forEach(image => {
let div = document.createElement('div');
div.className = 'col-lg-3 col-md-4 col-xs-6 img-item mb-2';
div.innerHTML = ` <img class="img-fluid img-effect img-thumbnail" onclick=selectItem(event,"${image.webformatURL}") src="${image.webformatURL}" alt="${image.tags}">`;
gallery.appendChild(div);
})
toggleSpinner();
}
const getImages = (query) => {
toggleSpinner();
dangerInfo(false);
imagesArea.style.display = 'none';
const url = (`https://pixabay.com/api/?key=${KEY}=${query}&image_type=photo&pretty=true`);
fetch(url)
.then(response => response.json())
.then(data => {
if ((data.hits).length > 0) {
showImages(data.hits);
}
else {
imagesArea.style.display = 'none';
dangerInfo(true);
toggleSpinner();
}
})
.catch(err => dangerInfo(true))
}
let slideIndex = 0;
const selectItem = (event, img) => {
let element = event.target;
element.classList.add('added');
element.classList.remove('img-effect')
let item = sliders.indexOf(img);
if (item === -1) {
sliders.push(img);
} else {
// sliders.pop(img);
sliders.splice(item, 1);
element.classList.toggle("added");
element.classList.toggle('img-effect')
}
}
var timer
const createSlider = () => {
// check slider image length
if (sliders.length < 2) {
alert('Select at least 2 image.')
return;
}
// crate slider previous next area
sliderContainer.innerHTML = '';
const prevNext = document.createElement('div');
prevNext.className = "prev-next d-flex w-100 justify-content-between align-items-center";
prevNext.innerHTML = `
<span class="prev" onclick="changeItem(-1)"><i class="fas fa-chevron-left"></i></span>
<span class="next" onclick="changeItem(1)"><i class="fas fa-chevron-right"></i></span>
`;
sliderContainer.appendChild(prevNext)
document.querySelector('.main').style.display = 'block';
// hide image aria
imagesArea.style.display = 'none';
let duration = document.getElementById('duration').value || 1000;
if (duration <= 400) {
duration = 1000;
if (confirm("slider duration will set to 1s default")) {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(sliderMoverCallback, duration);
lastSetDuration = duration;
}
else {
imagesArea.style.display = 'block';
}
}
else {
sliders.forEach(slide => {
let item = document.createElement('div')
item.className = "slider-item";
item.innerHTML = `<img class="w-100"
src="${slide}"
alt="">`;
sliderContainer.appendChild(item)
})
changeSlide(0)
timer = setInterval(sliderMoverCallback, duration);
lastSetDuration = duration;
}
}
const sliderMoverCallback = () => {
changeSlide(++slideIndex);
}
// change slider index
const changeItem = index => {
changeSlide(slideIndex += index);
}
// change slide item
const changeSlide = (index) => {
const items = document.querySelectorAll('.slider-item');
if (index < 0) {
slideIndex = items.length - 1
index = slideIndex;
};
if (index >= items.length) {
index = 0;
slideIndex = 0;
}
items.forEach(item => {
item.style.display = "none"
})
items[index].style.display = "block"
}
function getInputValue() {
document.querySelector('.main').style.display = 'none';
clearInterval(timer);
const search = document.getElementById('search');
getImages(search.value)
sliders.length = 0;
}
const triggerSearchBtn = inputField.addEventListener('keypress', function (event) {
if (event.key === 'Enter') {
getInputValue();
}
})
sliderBtn.addEventListener('click', function () {
createSlider()
})
sliderContainer.addEventListener('mouseover', () => {
clearInterval(timer);
timer = undefined;
})
sliderContainer.addEventListener('mouseout', () => {
if (timer === undefined) { // if no animation is performing now then start it
timer = setInterval(sliderMoverCallback, lastSetDuration)
}
})
//Bonus Marking javascript
const toggleSpinner = () => {
const spinner = document.getElementById('spinner');
spinner.classList.toggle('d-flex');
}
const dangerInfo = (show) => {
const error = document.getElementById('error');
if (show) {
error.classList.add('d-flex');
}
else {
error.classList.remove('d-flex');
}
}
P.S。我肯定会做一些重构。很难阅读和找到你需要的东西。